4

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.

user1329572
  • 6,176
  • 5
  • 29
  • 39
  • 1
    Meaning "why did they use so much inheritance"? History. Swing was done before "favor" was agreed upon. – duffymo Jul 10 '12 at 14:42
  • 1
    @duffymo, Your understanding of the question is wrong. I'm not talking about how the Swing framework was designed, but about how to design a framework around it. – user1329572 Jul 10 '12 at 14:43
  • 1
    OK, then I'd say that composition over inheritance goes double for Swing. There are few reasons good enough where you need to extend a Swing class. Composition is all you need. – duffymo Jul 10 '12 at 14:50

2 Answers2

6

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();
Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111
4

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.

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75