Use super
only when you really need to. If you override setSize()
then you would find the second example would not call your overridden methods. This is not necessarily desired behaviour and therefore you should generally just call methods without the super
prefixing operator. It's generally best to write code such that it can be extended or maintained without having to worry about whether or not some overrides will actually override from certain methods or not. Also see Vulcan's comment rendering the issue null and void.
Java this and super keywords
Question
I've got a question about Java this and super keywords, let's take some examples
Firts example
import java.awt.*;
public class Main extends Frame {
//constructor of the class
public Main () {
super ("My frame");
setSize (200,100);
setVisible (true);
}
public static void main (String [] args) {
new Main ();
}
}
second example
import java.awt.*;
public class Main extends Frame {
//constructor of the class
public Main () {
//here the difference from example 1
super ("My frame");
super.setSize (200,100);
super.setVisible (true);
}
public static void main (String [] args) {
new Main ();
}
}
Which example is better and why?
Now let's take some examples about this keyword
public class Main {
public void print () {
System.out.println ("Hi");
}
public static void main (String [] args) {
print();
}
}
Second example
public class Main {
public void print () {
System.out.println ("Hi");
}
public static void main (String [] args) {
//here the difference
this.print();
}
}
Which is better and why? Thank you for your answers
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow