• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

HAS-A vs IS-A in OOP C#

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
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)

  • 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
  • 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();
  • Car HAS-A Engine.
? Summary Table:

AspectIS-AHAS-A
MeaningInheritance (child ← parent)Composition (class contains)
Implementationclass B : A {}class A { B b; }
ExampleDog : Animal Car has Engine
Use CaseReuse behavior via inheritanceDelegate tasks via composition
PolymorphismSupportedNot 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).


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу