Java Swing – When to Extend a Class

inheritancejavaobject-orientedprogramming practices

My current understanding of Inheritance implementation is that one should only extend a class if an IS-A relation is present. If the parent class can further have more specific child types with different functionality but will share common elements abstracted in the parent.

I'm questioning that understanding because of what my Java professor is recommending us to do. He has recommended that for a JSwing application we are building in class

One should extend all JSwing classes (JFrame,JButton,JTextBox,etc) into separate custom classes and specify GUI related customisation in them (like the component size, component label, etc)

So far so good, but he further goes on to advise that every JButton should have its own custom extended class even though the only distinguishing factor is their label.

For e.g. If the GUI has two buttons Okay and Cancel. He recommends they should be extended as below:

class OkayButton extends JButton{
    MainUI mui;
    public OkayButton(MainUI mui) {
        setSize(80,60);
        setText("Okay");
        this.mui = mui;
        mui.add(this);        
    }
}

class CancelButton extends JButton{
    MainUI mui;
    public CancelButton(MainUI mui) {
        setSize(80,60);
        setText("Cancel");
        this.mui = mui;
        mui.add(this);        
    }
}

As you can see the only difference is in the setText function.

So is this standard practice?

Btw, the course where this was discussed is called Best Programming Practices in Java

[Reply from the Prof]

So I discussed the problem with the professor and raised all the points mentioned in the answers.

His justification is that subclassing provides reusable code while following GUI design standards. For instance if the developer has used custom Okay and Cancel buttons in one Window, it will be easier to place the same buttons in other Windows as well.

I get the reason I suppose, but still it's just exploiting inheritance and making code fragile.

Later on, any developer could accidently call the setText on an Okay button and change it. The subclass just becomes nuisance in that case.

Best Answer

This violates the Liskov Substitution Principle because an OkayButton cannot be substituted in any place a Button is expected. For example, you can change the label of any button as you like. But doing that with an OkayButton violates its internal invariants.

This is a classic misuse of inheritance for code reuse. Use a helper method instead.

Another reason not to do this is that this is just a convoluted way of achieving the same thing that linear code would.

Related Topic