I know the advantages of inheritance in Java, but it is somewhat difficult for me to accept that it has disadvantages too. Can anybody give me a bad example of inheritance in Java?
The disadvantage of class inheritance is that the subclass becomes dependent on the parent class implementation. This makes it harder to reuse the subclass, especially if part of the inherited implementation is no longer desirable.
The reason behind this is to prevent ambiguity. Consider a case where class B extends class A and Class C and both class A and C have the same method display(). Now java compiler cannot decide, which display method it should inherit. To prevent such situation, multiple inheritances is not allowed in java.
Fragility of Inheritance This often leads to broken code, even when the IS-A criterion is met. This architectural problem is known as the fragile base class problem in object-oriented programming systems. The obvious reason for this problem is that the developer of a base class has no idea of the subclass design.
Stack extends Vector
. A stack is not a vector. Properties extends Hashtable
. A table of properties is not a hash table.See this answer for a quote from Effective Java.
It was easy to write the Stack
implementation by using what is already implemented in Vector
(likewise for Properties
), but it created problems - see here
One example is the old pattern of implementing constant interfaces (an interface containing only immutable fields), then classes wishing to use these constants would implement this interface for convenience. The problem is that your class now inherits the API of this interface and extensions to it's design may harm your API in the future.
The use of constant interfaces in this way is generally considered an anti-pattern these days. Since Java 5, you can use enums instead of interfaces full of constants and static imports instead of defining constant interfaces.
From Effective Java by Josh Bloch:
The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With