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

  • A+
Category:Languages

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?

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: