I have been programming java for like a year or more, and i have always used the this
and super
keywords.
And yesterday my mate read one source of mine, and told me not to over use it unless you are overriding the method.
class A extends JPanel {
public A {
super.setSize(400, 400);// instead of not using super keyword
}
}
But what he meant on how to use it, is this:
class A extends JPanel {
public A {
super.setSize(4,4);
}
public void setSize(int a, int b) {}
}
So the language will know that your constructor calls the parent method and not local.
Should i only use the the keywords in this situation only or use the keywords everywhere for better readibly?
I know that this
keyword is returning the whole local instance including the parent and all of its parents and interfaces.
And the super
keyword returns the instance of the parent class and all of its instances (parents and interfaces).
But my question is, should you always use these keywords?
super.method
is if you then overridemethod
within the same class,method
will no longer be called, but instead the parent implementation will be called, this introduces unnecessary risk into the code which could produce unexpected results. Of course, you could usesuper.method
to skip of the new implementation if you wanted to (I've done this withsetVisible
when I've wanted to do fading animation) - You just need to beware of the risk that usingsuper
can introduce...super.xxx
with) to ensure that you hadn't done something funny with them (espeicallysetVisible
) which you were trying to circumvent...