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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With