简体   繁体   中英

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

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.

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM