【发布时间】:2016-03-20 19:03:44
【问题描述】:
我有一个子类 ScottishPerson,它继承自类 BritishPerson。
class BritishPerson {
public String name = "A british name";
public void salute() {
System.out.println("Good Morning!");
}
}
class ScottishPerson extends BritishPerson {
public String name = "A scottish name "; //Variable overriding
public String clanName = "MacDonald";
public void salute() //Method overriding
{
System.out.println("Madainn Mhath!");
}
public void warcry() {
System.out.println("Alba Gu Brath!");
}
}
class Driver {
public static void main(String[] args) {
ScottishPerson scottishPerson = new ScottishPerson(); //Created as a subclass, can always be upcasted.
BritishPerson britishPerson = new BritishPerson(); //Created as the superclass, throws an error when downcasted.
BritishPerson britishPersonUpcasted =
new ScottishPerson(); //Created as the subclass but automatically upcasted, can be downcasted again.
//Checking the methods and parameters of scottishPerson
scottishPerson.salute();
scottishPerson.warcry();
System.out.println(scottishPerson.name);
System.out.println(scottishPerson.clanName);
//Checking the methods and parameters of britishPerson
britishPerson.salute();
System.out.println(britishPerson.name);
//Checking the methods and parameters of britishPersonUpcasted
britishPersonUpcasted.salute();
System.out.println(britishPersonUpcasted.name);
}
}
运行代码,这是输出。
Madainn Mhath!
Alba Gu Brath!
A scottish name
MacDonald
Good Morning!
A british name
Madainn Mhath!
A british name
这就是混乱所在。将ScottishPerson 向上转换为BritishPerson 会将变量名称更改为在超类中定义的名称。只存在于子类中的方法和变量,例如warcry() 和clanName 将被丢弃。但是,在向上转换的类上调用方法salute() 仍然会返回基于子类实现的字符串。
是不是因为当我创建对象britishPerson 时,我只初始化BritishPerson 类,而当我创建对象britishPersonUpcasted 时,我同时创建了BritishPerson 类和ScottishPerson 类,这导致了永久覆盖salute() 方法?
【问题讨论】:
标签: java inheritance subclass superclass upcasting