为了理解向下转换,我做了以下代码。
class Vehicle{
protected int tyres=0;
protected String name="default";
Vehicle(){
}
Vehicle(String aname){
name=aname;
}
//abstract void setTyres(int number);
public void print(){
System.out.println(name+":"+tyres);
}
}
class TwoWheeler extends Vehicle{
TwoWheeler(){
tyres=2;
}
public void print(){
System.out.println(name+":"+tyres);
}
}
class FourWheeler extends Vehicle{
FourWheeler(){
tyres=4;
}
public void print(){
System.out.println(name+":"+tyres);
}
}
public class vehicles {
public static void main(String[] args) {
try{
Vehicle v= new Vehicle("Dummy");
v.print();
v= new TwoWheeler();
v.print();
}
catch(Exception e){
System.out.println(e.toString());
}
}
}
现在输出是 假:0 默认值:2
虽然我期待Dummy:0 Dummy:2 看起来第二次调用父构造函数?请解释这里发生的事情。 另外,如何在不调用父项的情况下进行向下转换?
答案 0 :(得分:0)
第二次调用父构造函数,因为您正在创建两个对象。
Vehicle v = new Vehicle("Dummy"); // first object created here
v.print();
v = new TwoWheeler(); // second object created here
您不能将基类实例的类型(例如您创建的第一个对象)更改为子类实例。
您可以做的是定义一个接受TwoWheeler
参数的Vehicle
构造函数,并使用传递的Vehicle
的属性初始化新实例。这称为复制构造函数。
TwoWheeler(Vehicle source) {
super (source.getName());
tyres=2;
}
您的main
将如下所示:
Vehicle v = new Vehicle("Dummy");
v.print();
v = new TwoWheeler(v);
v.print();
答案 1 :(得分:0)
Vehicle v = new Vehicle("Dummy");
//First object create with following properties,
name = "Dummy"
tyres = 0
v = new TwoWheeler();
//Second object created with following properties,
/* Flow goes like,
TwoWheeler() constructor called,
flow again go up to super and assign name with "default",
while flow come back to TwoWheeler() constructor ,
tyres = 2 assign.
*/
最后,根据您显示的内容输出。 进入