Object-Oriented Programming – How Can an Object Have Many Types?

object-orientedtype-systems

I am currently reading Design Patterns – Elements of Reusable Object-Oriented Software. I am in chapter 1 at page 16 in section Class versus Interface Inheritance. There in the last line of the page it says " An object can have many types, and objects of different classes can have the same type. "

I think I understand the second part of the sentence, how objects of different classes can have same types. It is possible by inheritance, if Base class and derived class have same interface.

My question is how can object have many types. Is it trying to say a derived object can have two type base and derived?

Best Answer

The big hint is in your question: "interface inheritance".

Basically, an interface is nothing but a set of method signatures. In a traditional OOP language, the only thing a class needs to do to satisfy an interface is to have implementations of those method signatures, and declare that it implements the interface. Since it's not inheriting implementations, there's no ambiguity or contradiction in having a single class implement several interfaces at once, or having several classes implement the same interface with different underlying data or algorithms.

For instance, here's some trivial Java code that declares a class which implements several other interfaces, and thus has all of their types at the same time:

public interface A { void a(); }
public interface B { void b(); }
public interface C { void c(); }
public interface D { void d(); }

public class IAmManyTypes implements A, B, C, D {
  public void a() {}
  public void b() {}
  public void c() {}
  public void d() {}
}
Related Topic