r/javahelp • u/reeegiii • Feb 17 '20
Difference between this and super when calling a method from a parent class
Could anyone please explain to me what is the difference between this and super in this context? The output for both is the same. When should I be using super vs this?
public class A {
public void doA() {
System.out.println("A");
}
}
class B extends A {
public void trySuper() {
super.doA();
}
public void tryThis() {
this.doA();
}
}
class C {
public static void main(String args[]) {
B b = new B();
b.trySuper();
b.tryThis();
}
}
22
Upvotes
1
u/abcoolynr Feb 18 '20
make doA in class A private and then try. super will work but not this.
1
u/reeegiii Feb 18 '20
I'm getting a syntax error for both try and super when I make it private. It only works with protected or public.
3
u/John_Taured Feb 17 '20
Try running this: