Java: Are this.foo() and super.foo() the same when foo() is in the super class?
Asked Answered
A

2

18

Say I have the following classes:

class Foo {
    protected void method() {}
}

class Bar extends Foo {

}

At this point, from the class Bar, I have access to method() in two ways:

  • super.method();
  • this.method();

From what I see, they seem to perform the same action. Is there a difference between these two in this context? Is there a preferred version to use if so?

Using super makes sense because method() is part of the super class. Using this makes sense too I suppose, as Bar will inherit the properties of the class Foo, and therefore method() as well, right?

Anglin answered 2/6, 2018 at 17:56 Comment(3)
In the situation you described, both variants have the same semantics. But normally, one uses this unless it is necessary to use super.Terrorstricken
Alright, cool. I was under the impression that super was possibly preferred if the method isn't overridden, as to point to where it's defined.Anglin
Only use this if you must. It hints that there is a reason for doing so, and that reason should be very clear.Namnama
M
18

Yes, this.foo() calls the same method as super.foo().

Note that there will be a difference if foo() is overridden in the child class. But in this case, it runs the same method implementation.

We use super.foo() when we need to specifically request that the superclass's method implementation be executed, when there's one available in the current class.

Using super makes sense because method() is part of the super class

Yes, but remember that the child class can change at some point and get an overridden foo(), in which case super.foo() may start calling the unintended implementation.
This is something to be aware of. For this reason, calling this.foo(), or unqualified foo() may be justified.

Micronesian answered 2/6, 2018 at 17:59 Comment(0)
D
12

Just be aware that the child can be overridden yet again:

public class Main {
  static class Foo {
    protected void method() {
      System.out.println("Bye");
    }
  }

  static class Bar extends Foo {
    {
      this.method();
      super.method();
    }
  }

  static class Baz extends Bar {
    protected void method() {
      System.out.println("Hi");
    }
  }

  public static void main(String[] args) {
    new Baz();
  }
}

Produces:

Hi
Bye

So, although this.method() and super.method() may behave the same in some cases, they do not produce the same byte-code.

Directorate answered 2/6, 2018 at 20:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.