r/javahelp • • 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

7 comments sorted by

3

u/John_Taured Feb 17 '20

Try running this:

public class A {

	public void doA() {
		System.out.println("A");
	}
}

class B extends A {

	public void trySuper() {
		super.doA();

	}

        @Override
        public void doA() {
                System.out.println("B");
        }

	public void tryThis() {
		this.doA();
	}
}

class C {
	public static void main(String args[]) {
		B b = new B();
		b.trySuper();
		b.tryThis();

	}
}

4

u/reeegiii Feb 17 '20

Right. So if a child class did not override the method, this and super are basically the same?

I know that they "do" the same thing because the output is the same on my original code. But I wanna know if there is something behind the scene going on in there.

4

u/desirecampbell Feb 17 '20

this always refers to the declared object, and super refers to its parent - but if this doesn't have something (a method or property) it's parent might, so the compiler will automatically try going up one generation. If that class doesn't have it, we go up another generation, and so on and so on.

In this case B doesn't have it's own doA() method, so when it uses it's parent's. This is exactly how toString() works.

2

u/DarthFloopy Feb 18 '20

To clarify:

The short story is: in practice, that's correct.

The slightly longer story is: a subclass inherits all members of its superclass, so in OP's example, class B has a doA() method even though it's not directly declared in the B source code. When you call this.doA() inside B, you are calling B's version, as opposed to super.doA() which calls A's version (which may or may not be the exact same -- it depends on whether class B overrides doA()).

There... is that complicated enough?

1

u/John_Taured Feb 17 '20

Yes, they are the same. You will use your parent's implementation unless you specifically override it.

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.