问题
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