to Extend or not to Extend
Hi,
I have a small code as in below:
Code:
package myPackage;
import javax.swing.JFrame;
public class SimpleInheritance {
public static void main (String args[]) {
JFrame myFrame = new JFrame();
myFrame.setSize(123,125);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}// end main
}// end class SimpleInheritance
My question is on extending:
If my class SimpleInheritance extends JFrame:
1) I will not need to use JFrame.EXIT_ON_CLOSE, but using only EXIT_ON_CLOSE will be enough since I will have access to the variable EXIT_ON_CLOSE.
2) I will be allowed to override methods that JFrame has.
Besides these two options, what else is extending providing me ?
Thank you.
Re: to Extend or not to Extend
There are dangers of extending a class when it is not necessary (when you are not altering the innate behavior of the class). I have run into this myself when subclassing JPanel and then giving this class two int fields, x and y with the expected setters and getters. Imagine my surprise when I could never draw the JPanel in the correct location because my unnecessary subclassing resulted in accidentally overriding JComponents getX() and getY() methods.
My advice -- don't subclass another class unless you have a very specific and important reason for doing so. Being able to access constants with less typing is not a good reason in my opinion.
Re: to Extend or not to Extend
In almost every case of an extended JFrame (and often with a JPanel) it is not a genuine extension, by which you are not adding functionality.
You are simply extending it to stick the code that fills the JFrame somewhere.
It's a bit like extending an ArrayList simply to write:
Code:
public MyArrayList extends ArrayList {
public MyArrayList() {
add(some object);
add(some other object);
etc etc.
}
}
Re: to Extend or not to Extend
Thank you..
So extending a JFrame is really not useful ? Or meaningful ?
Re: to Extend or not to Extend
Quote:
Originally Posted by
fatabass
Thank you..
So extending a JFrame is really not useful ? Or meaningful ?
It is useful and meaningful, if you're actually changing some behavior, such as overriding paintComponent (in which case, extend a JPanel and put it in a JFrame). But if you're only doing it to get around typing JFrame.EXIT_ON_CLOSE, then don't do it. Even if you did extend JFrame, it's bad practice to refer to static values without using the class name.
But if you really want to get around it and don't mind that it's lazy and a bit terrible, you can use a static import:
Code:
import static javax.swing.JFrame.EXIT_ON_CLOSE;
public Lazy(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}