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.
JButton
and call public methods in its constructor, when you can simply create aJButton
and call those same public methods outside of the class?