在定義中是子類向父類轉型稱為向上轉型,父類向子類轉型是向下轉型(必須先向上轉型過,才能向下轉型),
但是在下面類定義后,我得到的結果卻不同。求大佬解惑
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值),這感覺是父類向子類轉型把,不是子類向父類轉型,求大佬解惑。
