Java Reference
In-Depth Information
Classroom Q & A
Q: I noticed in the Salary class you used this.name in the mailCheck()
method and super.name in the computePay() method. How do
you know which one to use?
A: It doesn't matter, as I demonstrated in the Salary class when I used
both this and super. The name field is inherited from the Employee
class. I can use super to access fields or methods in the parent.
Q: Then why can you use this.name also?
A: Because a Salary object has a field called name, and an object can
use this to access its own fields.
Q: So super and this refer to the same thing?
A: No! When a child object is referring to an inherited field or
method, then this or super can be used. However, when a child is
accessing a field or method from its own class, then only the this
reference can be used, as with this.salary in the mailCheck()
method of the Salary class. Using super.salary in that case would
not compile because the parent class does not have a salary field.
Q: Then why is the super reference needed?
A: The super reference must be used when a child class wants to
invoke an overridden parent class method.
The super keyword has another use that is not related to overridden
methods. This other use of the super keyword is discussed later in this
chapter in the section Invoking a Parent Class Constructor .
The final Keyword
We have seen the final keyword used for creating constant variables. A final
variable cannot be changed after it has been assigned a value.
Now that we have seen inheritance and method overriding, I can show you
the other two uses of the final keyword.
Final class. A class can be declared final. A final class cannot be subclassed.
Final method.
A method can be declared final. A final method cannot be
overridden.
Search WWH ::




Custom Search