在定义中是子类向父类转型称为向上转型,父类向子类转型是向下转型(必须先向上转型过,才能向下转型),
但是在下面类定义后,我得到的结果却不同。求大佬解惑
class superclass{
public int x = 100;
public void printinfo() {
System.out.println("x = "+this.x);
}
}
class sonclass extends superclass{
public int x = 50;
public int y = 200;
public void printinfo() {
System.out.println("x = "+this.x+" y = "+this.y);
}
}
import java.util.*;
public class zhuanxing {
public zhuanxing() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
superclass c1 = new superclass();
sonclass c2 = new sonclass();
c1.printinfo();
c2.printinfo();
c1 = c2;
c1.printinfo();
c1.printinfo();
c2 = (sonclass)c1;
System.out.println("向上转型后,能向下转型!");
c1.printinfo();
c2.printinfo();
}
}
运行结果:
x = 100
x = 50 y = 200
x = 50 y = 200
x = 50 y = 200
向上转型后,能向下转型!
x = 50 y = 200
x = 50 y = 200
感觉所谓的向上转型和实际不符合,例如:
c1=c2,这个语句是向上转型;但是实际结果是c1变成了子类类型(c1自动调用子类函数,且有了y值),这感觉是父类向子类转型把,不是子类向父类转型,求大佬解惑。