12

Today a professor of mine commented that he found it odd that while SWT's philosophy is one of making your own controls by composition, Swing seems to favour inheritance.

I have almost no contact with both frameworks, but from what I remember in C#'s Windows Forms one usually extends controls, just like Swing.

Being that generally people tend to prefer composition over inheritance, why didn't Swing/Windows Forms folks favour composition instead of inheritance?

5 Answers5

7

JComponent exposes a lot of functionality. If JComponent was an interface and components were implemented with composition, simple components would need to have dozens of trivial method wrappers, e.g.

class MyComponent implements JComponent {
    JPanel panel;
    public boolean contains(int x, int y) {
        return panel.contains(x, y);
    }
    ...
}

There's also an efficiency reason to prefer inheritance over composition -- overriding costs nothing (assuming no super call), while composition costs an extra INVOKEVIRTUAL. I don't know if this influenced the design of Swing, but it's a big concern for collection classes.

2

The Swing Framework is actually designed in accordance with the Composite Design Pattern. Granted that there is a lot of inheritance in there, but you would usually compose your own forms using composition. That is, a form is a composition of intermediate level containers and controls.

1

With Java, its a lot easier to end up using inheritance just because everything is virtual. Need to fix a "feature" in JTable/JFrame? Extend it, override the problem methods, and then use your Table/Frame everywhere instead.

I think with things like WPF, where data binding is a primary feature of the design, makes it a lot easier to do composition instead of inheritance.

1

In Effective Java, Item 17, Bloch mentions that a class designed for inheritance "must document its self-use of overridable methods." A hallmark of this is the phrase this implementation. You'll see it in classes like JTable and JInternalFrame. It's one measure of inheritance by design in Swing.

trashgod
  • 158
-2

From C# 3.5, we have a concept called as Extension Methods which allows the concept of composition than inheritance.

In this process, we implement an extended functionality to an existing class just by adding an extension class which renders the new feature to the existing class.

You can refer here for more details

Saravanan
  • 133
  • 8