- Регистрация
- 1 Мар 2015
- Сообщения
- 1,481
- Баллы
- 155
In Object-Oriented Programming (OOP), HAS-A and IS-A relationships are fundamental concepts used to describe how classes and objects relate to each other. While these apply to many OOP languages like Java or C#, the principles are universal.
IS-A Relationship (Inheritance)
public class Animal {
public void Eat() => Console.WriteLine("Eating...");
}
public class Dog : Animal {
public void Bark() => Console.WriteLine("Barking...");
}
// Usage
Dog dog = new Dog();
dog.Eat(); // Inherited
dog.Bark(); // Dog-specific
HAS-A Relationship (Composition)
public class Engine {
public void Start() => Console.WriteLine("Engine starting...");
}
public class Car {
private Engine engine = new Engine();
public void StartCar() {
engine.Start();
Console.WriteLine("Car started.");
}
}
// Usage
Car car = new Car();
car.StartCar();
? Best Practice
- Represents: A subtype relationship (child → parent)
- Mechanism: Achieved through inheritance.
- Implies: The derived class is a type of the base class.
- Usage: Use when there’s a clear hierarchical relationship.
public class Animal {
public void Eat() => Console.WriteLine("Eating...");
}
public class Dog : Animal {
public void Bark() => Console.WriteLine("Barking...");
}
// Usage
Dog dog = new Dog();
dog.Eat(); // Inherited
dog.Bark(); // Dog-specific
- Dog IS-A Animal.
- Represents: A class containing references to other classes as members.
- Mechanism: Achieved through composition (member variables).
- Implies: A class has a reference to another class.
- Usage: Use when one object uses another.
public class Engine {
public void Start() => Console.WriteLine("Engine starting...");
}
public class Car {
private Engine engine = new Engine();
public void StartCar() {
engine.Start();
Console.WriteLine("Car started.");
}
}
// Usage
Car car = new Car();
car.StartCar();
- Car HAS-A Engine.
| Aspect | IS-A | HAS-A |
|---|---|---|
| Meaning | Inheritance (child ← parent) | Composition (class contains) |
| Implementation | class B : A {} | class A { B b; } |
| Example | Dog : Animal | Car has Engine |
| Use Case | Reuse behavior via inheritance | Delegate tasks via composition |
| Polymorphism | Supported | Not directly |
- Prefer composition (HAS-A) over inheritance (IS-A) when possible (favor delegation for flexibility).
- Use IS-A only when the subclass truly fulfills the contract of the superclass (Liskov Substitution Principle).