What can be the bad example of inheritance in Java

2019-05-01 01:49发布

问题:

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?

回答1:

  • 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



回答2:

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.



回答3:

There's a pretty good article here talking about the use of inheritance vs. composition in Java, including examples of when and why to use one over the other. There's also an interview here which discussed the subject (referencing the Gang of Four edict to "favor composition over inheritance").

It's a very broad and, at least for me, very interesting subject actually. A lot of beginner programmers get some inheritance going and start down a bad design path, not always learning how polymorphism works and what design patterns and techniques they can take advantage of to write better software. If you're an object-oriented programmer, you can never learn too much about polymorphism, interfaces, inheritance, composition, abstractions, etc.



回答4:

I believe as long as it follows the "is-a" guideline and the person implementing it understands it and doesn't make a mess of it there aren't really any disadvantages.



回答5:

Immaturity is the incapacity to use one's intelligence without the guidance of another. Immanuel Kant

If you say: "It is difficult for you to accept, that it has disadvantages too.", then I understand it as - You know about disadvantages and you have some moral conflicts or confusion of ideas, that question your knowledge nature. Same way as to "hear" and "listen" are two different things, I can't make you understand, if you do not try yourself.

If you want to understand, try reading a book, for example:

  • Effective Java (item 16) : favor composition over inheritance ( Link )