Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can be the bad example of inheritance in Java?

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?

like image 623
Supereme Avatar asked Mar 20 '11 12:03

Supereme


People also ask

What are the disadvantages 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.

Where inheritance should not be used in Java?

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.

What is the major problem with inheritance 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.


2 Answers

  • 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

like image 174
Bozho Avatar answered Oct 05 '22 13:10

Bozho


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.

like image 27
krock Avatar answered Oct 05 '22 12:10

krock