Good reasons to prohibit inheritance in Java?

2019-01-03 07:59发布

What are good reasons to prohibit inheritance in Java, for example by using final classes or classes using a single, private parameterless constructor? What are good reasons of making a method final?

11条回答
Lonely孤独者°
2楼-- · 2019-01-03 08:27

Your best reference here is Item 19 of Joshua Bloch's excellent book "Effective Java", called "Design and document for inheritance or else prohibit it". (It's item 17 in the second edition and item 15 in the first edition.) You should really read it, but I'll summarize.

The interaction of inherited classes with their parents can be surprising and unpredicatable if the ancestor wasn't designed to be inherited from.

Classes should therefore come in two kinds :

  1. Classes designed to be extended, and with enough documentation to describe how it should be done

  2. Classes marked final

If you are writing purely internal code this may be a bit of overkill. However the extra effort involved in adding five characters to a class file is very small. If you are writing only for internal comsumption then a future coder can always remove the 'final' - you can think of it as a warning saying "this class was not designed with inheritance in mind".

查看更多
虎瘦雄心在
3楼-- · 2019-01-03 08:31

One reason to make a class final would be if you wanted to force composition over inheritance. This is generally desirable in avoiding tight coupling between classes.

查看更多
叼着烟拽天下
4楼-- · 2019-01-03 08:33

If you mark classes and methods as final, you may notice a small performance gain, since the runtime doesn't have to look up the right class method to invoke for a given object. Non-final methods are marked as virtual so that they can be properly extended if needed, final methods can be directly linked or compiled inline in the class.

查看更多
男人必须洒脱
5楼-- · 2019-01-03 08:37

Inheritance is like a chainsaw - very powerful, but awful in the wrong hands. Either you design a class to be inherited from (which can limit flexibility and take a lot longer) or you should prohibit it.

See Effective Java 2nd edition items 16 and 17, or my blog post "Inheritance Tax".

查看更多
Root(大扎)
6楼-- · 2019-01-03 08:37

You want to make a method final so that overriding classes does not change its behavior. When you want to be able to change the behavior make the method public. When you override a public method it can be changed.

查看更多
forever°为你锁心
7楼-- · 2019-01-03 08:40

You might want to make a method final so that overriding classes can't change behavior that is counted on in other methods. Methods called in constructors are often declared final so you don't get any unpleasant surprises when creating objects.

查看更多
登录 后发表回答