Hey after all the fuss about Composition and inheritance and drilling in the fact that Composition is superior,I dont understand why the need to know ploymorphism?Since it is gotten through inheritance.Is this a joke?
Whats the industry practice?Are they use widely?

Recommended Answers

All 2 Replies

Well, first off, it isn't really the case that composition is superior to inheritance, so much as that they are useful for different things, and that inheritance lends itself to misuse more than composition does. The real knock against inheritance is about 'spaghetti inheritance', which is where you are inheriting from multiple base classes which aren't conceptually super-classes of the class, just to get some functionality that the base class possesses. It's a common design anti-pattern, one which has given inheritance a bad name. That, plus the fact that composition is more generally applicable than inheritance, is the real reason they drill into students to use composition rather than inheritance.

The general rule is that you should only inherit from those parent classes which the subclass clearly is a special case of. One common test for the validity of inheritance is the Liskov Substitution Principle, which (informally) states that for a given parent class, it should be possible to substitute an object of any subclass and have the object respond usefully to all possible messages which could be passed to a parent class object.

As for polymorphism, it is actually used quite widely, but again, it lends itself to misuse. Polymorphism is primarily applicable when you have a subclass which adds to the behavior of a parent class, rather than one which replaces the existing behavior entirely. For example, the BufferedReader class inherits the Reader class, but adds the buffering behavior to the input methods.

Note that the entire concept of abstract classes depends on polymorphism: the abstract methods are always polymorphic, as the parent class has no implementation to begin with.

polymorphism isn't only achieved by extending classes, but also by implementing interfaces.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.