AP计算机教程9-6:使用super调用被重写的方法
有时你会希望child class的method能比parent class中的对应物做得更多一些。你还是希望执行parent method,但同时完成一些别的工作。那么怎么在重写方法之后仍然调用它呢?你可以使用super.method()来做到这一点。
public class Person
{
private String name = null;
public Person(String theName)
{
name = theName;
}
public String getFood()
{
return "Hamburger";
}
public static void main(String[] args)
{
Person p = new Student("Javier");
System.out.println(p.getFood());
}
}
class Student extends Person
{
private int id;
private static int nextId = 0;
public Student(String theName)
{
super(theName);
id = nextId;
nextId++;
}
public String getFood()
{
String output = super.getFood();
return output + " and Taco";
}
public int getId() {return this.id;}
public void setId (int theId)
{
this.id = theId;
}
}
这是如何实现的?记住每个object都保存有创建它的class的引用。在调用method时,会一直沿着继承关系向祖先追溯,直至找到需要的method定义。即便是被重写的method仍然还是保留在程序中的。
当student的getFood() method被调用时,首先会开始执行student.getFood()。在执行到super.getFood()这条语句后,就会转而执行Person.getFood()并返回字符串Hamburger。然后student.getFood()会被继续执行完,返回Hamburger and Taco。
0:00
Given the following class declarations, and assuming that the following declaration appears in a client program: Base b = new Derived();, what is the result of the call b.methodOne();?
public class Base
{
public void methodOne()
{
System.out.print("A");
methodTwo();
}
public void methodTwo()
{
System.out.print("B");
}
}
public class Derived extends Base
{
public void methodOne()
{
super.methodOne();
System.out.print("C");
}
public void methodTwo()
{
super.methodTwo();
System.out.print("D");
}
}
注意此时
super.methodOne()中调用的methodTwo()会是Derived中的。2
0 条评论