|
|
|
|
|
by llamaz
3571 days ago
|
|
If you think inheritance is central to OOP, then you are mistaken. The most important aspect of OOP is dynamic dispatch (e.g. objects accessed through Java interfaces), and that's closely related to the idea of messaging. Have a read of what other people are writing here. |
|
Java Interfaces are in fact an example of inheritance. Moreover, they are an example of "non OOP inheritance": it's an inheritance of type checking that actually doesn't bring any attributes to an object. It exists in support of compiler diagnostics and compile-time optimization of dispatch.
In some languages (even ones that do support inheritance very well) objects of different types can be substitutable over a common set of functions without any explicit inheritance of interfaces or anything.
We can make a Dog and Cat class in complete isolation from each other, with no common dependency, and give them a speak() method. Then pass an instance of either class to some function which just calls arg.speak(). This produces "bark!" if arg is a Dog, or "meow!" if it is a Cat.
A Java-style interface just makes this dispatch easier to optimize via a static type system, and to implement checks. The function cannot call arg.speak() unless arg is a reference to an ICanSpeak type. That is assured externally because code which passes anything else to that function will not compile. Thus Dog and Cat must inherit this ICanSpeak, which causes their instances to be eligible as arguments to that function. When they implement speak(), their implementation is type-checked against ICanSpeak's speak(): to have the right number of properly typed arguments.