- 論壇徽章:
- 0
|
Chapter5
Classes, Superclasses, and Subclasses(類,超類和子類)
如果一個(gè)子類的方法(如:getSalary)覆蓋了超類的方法(如:getSalary),那么當(dāng)子類要調(diào)用超類中方法時(shí)須加super關(guān)鍵詞(即super.getSalary),以指明調(diào)用的是超類中方法,否則將調(diào)用子類中的同名方法,也就是調(diào)用最接近這個(gè)方法的類的方法(聽起來好別扭哦 ^_^)
However, some of the superclass methods are not appropriate for
the Manager subclass. In particular, the getSalary method
should return the sum of the base salary and the bonus. You need to supply a new
method to override the superclass method:
class Manager extends Employee
{
. . .
public double getSalary()
{
. . .
}
. . .
}
How can you implement this method? At first glance, it appears
to be simple: just return the sum of the salary and bonus
fields:
public double getSalary()
{
return salary + bonus; // won't work
}
However, that won't work. The getSalary method of the
Manager class has no direct access to the
private fields of the superclass. This means that the getSalary
method of the Manager class cannot directly access the salary
field, even though every Manager object has a field called
salary. Only the methods of the Employee class have access to
the private fields. If the Manager methods want to access those private
fields, they have to do what every other method does—use the public interface,
in this case, the public getSalary method of the Employee
class.
So, let's try this again. You need to call getSalary
instead of simply accessing the salary field.
public double getSalary()
{
double baseSalary = getSalary(); // still won't work
return baseSalary + bonus;
}
The problem is that the call to getSalary simply calls
itself, because the Manager class has a
getSalary method (namely, the method we are trying to implement). The
consequence is an infinite set of calls to the same method, leading to a program
crash.
We need to indicate that we want to call the getSalary
method of the Employee superclass, not the current class. You use the
special keyword super for this purpose. The call
super.getSalary()
calls the getSalary method of the Employee
class. Here is the correct version of the getSalary method for the
Manager class:
public double getSalary()
{
double baseSalary = super.getSalary();
return baseSalary + bonus;
}
this關(guān)鍵詞有兩種含義:
1、表示當(dāng)前類的一個(gè)引用
2、調(diào)用同一個(gè)的類的另一個(gè)構(gòu)造器
同樣,super關(guān)鍵詞也有兩種含義:
1、 調(diào)用超類的方法
2、調(diào)用超類的構(gòu)造器
本文來自ChinaUnix博客,如果查看原文請點(diǎn):http://blog.chinaunix.net/u/20527/showart_144003.html |
|