A Question on Object Orientation from a .Net Forum

What are the advantages/disadvantages when choosing between inheritance, interfaces, aggregation, delegation etc?

David Ringsell’s answer

Inheritance, interfaces, aggregation and delegation cover a lot of features in OO programming. Broadly you are talking about relationships between classes. This will depend on the context, for example how complex is the domain you are modeling.

This is a brief summary. I hope a definition of the terms will help you evaluate these different OO approaches as a starting point.

Inheritance is a powerful feature that allows to create a family of related classes. First create a base class, e.g. a mammal, then inherit from this to create a derived class e.g. cat. The derived class can override & extend members (methods, properties, indexers, and events) of the base class. When doing an OO design, inheritance is a good place to start. Identify common members and put them in a base class, then inherit from this.

// TextBox derives from Control
public class TextBox : Control
{
// a new version (note keyword) because in the
// derived method we change the behavior
public new void DrawControl()
{
   base.DrawControl(); // invoke the base method
   Console.WriteLine("Writing string to the textbox: {0}",
mTextBoxContents);
}
}

Interfaces contain the members of a class, but not their code. The class that implements the interfaces agrees to implement all the interface members.

// define the interface
interface IClient
{
   void Order(int orderNum);
   string name { get; set; }
   string address { get; set; }
}

Aggregation is about creating a class relationship. For example, a Car class can aggregate the Wheel class.  To do this, the Car class can have a Wheels property that exposes a collection of objects of type Wheel.

A delegate points to any method, just like variables points to any value. The delegate can abstract any method with matching signature: e.g. same parameter types & number. Useful for async programming techniques.

// Declare delegate -- defines required signature:
delegate void SampleDelegate(string message);
// Instantiate delegate with named method:
   SampleDelegate d1 = SampleDelegateMethod;
// Instantiate delegate with anonymous method:
   SampleDelegate d2 = delegate(string message)
Scroll to Top
Share via
Copy link