DEV Community

Taki
Taki

Posted on

HAS-A vs IS-A in OOP C#

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)

  • 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.

🔹 C# Syntax Example:

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
Enter fullscreen mode Exit fullscreen mode
  • Dog IS-A Animal.

HAS-A Relationship (Composition)

  • 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.

🔹 C# Syntax Example:

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();
Enter fullscreen mode Exit fullscreen mode
  • Car HAS-A Engine.

🔁 Summary Table:

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

🧠 Best Practice

  • 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).

Top comments (0)