Java Swing: Does the phrase “favor composition over inheritance” apply?

回眸只為那壹抹淺笑 提交于 2019-12-10 16:52:29

问题


Does the phrase "favor composition over inheritance" apply to Swing components? I'd like to gather some professional opinions about the subject and which code is easier to maintain before I go ahead and design a UI.


回答1:


Does the phrase "favor composition over inheritance" apply to Swing components?

Yes.

The only time I extend a Swing component is when I need to override one or more of the methods. For instance, I'll extend a JPanel when I want to override the paintComponent method.

All other times, my class will contain the Swing component(s) I need. This allows me to separate my class methods:

frame.getMethod();

from the Swing component class methods:

frame.getFrame().getPreferredSize();



回答2:


Try this..

1. I usually prefer using Composition over Inheritance, if i do NOT to use all the methods of a class or those methods dont apply to my class.

2. Composition works with HAS-A relationship..

eg: Bathroom HAS-A Tub

   Bathroom cannot be a Tub

3. Inheritance is used at its best, when its used to force some features down to its subclasses.

eg:

Every Four Wheeler must have Steering, Brakes, Lights, Windows, etc...

Must be able to Accelerate, Apply Brakes, etc....

So its subclasses must have the features that makes it a Four Wheeler.



来源:https://stackoverflow.com/questions/11415813/java-swing-does-the-phrase-favor-composition-over-inheritance-apply

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!