Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 681
Magnus Bull Avatar asked Jun 02 '18 17:06

Magnus Bull


People also ask

What is foo function in Java?

Foo (pronounced FOO) is a term used by programmers as a placeholder for a value that can change, depending on conditions or on information passed to the program. Foo and other words like it are formally known as metasyntactic variables.

Can we use super super in Java?

The super keyword in Java is a reference variable that is used to refer parent class objects. The super() in Java is a reference variable that is used to refer parent class constructors. super can be used to call parent class' variables and methods. super() can be used to call parent class' constructors only.

What is called by the call to super () below?

super() is called implicitly before the first line of any constructor, unless it explicitly calls super() or an overload itself, or the class is java. lang. Object. Follow this answer to receive notifications.


1 Answers

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.

like image 130
ernest_k Avatar answered Oct 01 '22 20:10

ernest_k