user1329572
user1329572

Reputation: 6406

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.

Upvotes: 5

Views: 638

Answers (2)

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51445

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

Upvotes: 7

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

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.

Upvotes: 4

Related Questions