Java 转型问题其实并不复杂,只要记住一句话:父类引用指向子类对象。
1 public class Zhuanxing1 { 2 static class Father { 3 public int money = 1; 4 5 public Father() { 6 System.out.println("father constructor " + money); 7 money = 2; 8 showMoney(); 9 } 10 11 public void showMoney() { 12 System.out.println("father : i have " + money); 13 } 14 } 15 16 static class Son extends Father { 17 public int money = 3; 18 19 public Son() { 20 System.out.println("son constructor " + money); 21 money = 4; 22 showMoney(); 23 } 24 25 public void showMoney() { 26 System.out.println("son: i have " + money); 27 } 28 } 29 30 public static void main(String[] args) { 31 Father father = new Son(); 32 father.showMoney(); 33 System.out.println("this gay have $ " + father.money); 34 } 35 }
father constructor 1
son: i have 0
son constructor 3
son: i have 4
son: i have 4
this gay have $ 2
什么叫父类引用指向子类对象?
从 2 个名词开始说起:向上转型(upcasting) 、向下转型(downcasting)。
举个例子:有2个类,Father 是父类,Son 类继承自 Father。
第 1 个例子:
Father f1 = new Son(); // 这就叫 upcasting (向上转型)
// 现在 f1 引用指向一个Son对象
Son s1 = (Son)f1; // 这就叫 downcasting (向下转型)
// 现在f1 还是指向 Son对象
第 2 个例子:
Father f2 = new Father();
Son s2 = (Son)f2; // 出错,子类引用不能指向父类对象
你或许会问,第1个例子中:Son s1 = (Son)f1; 问为什么是正确的呢。
很简单因为 f1 指向一个子类对象,Father f1 = new Son(); 子类 s1 引用当然可以指向子类对象了。
而 f2 被传给了一个 Father 对象,Father f2 = new Father(); 子类 s2 引用不能指向父类对象。
总结:
1、父类引用指向子类对象,而子类引用不能指向父类对象。
2、把子类对象直接赋给父类引用叫upcasting向上转型,向上转型不用强制转换吗,如:
Father f1 = new Son();
3、把指向子类对象的父类引用赋给子类引用叫向下转型(downcasting),要强制转换,如:
f1 就是一个指向子类对象的父类引用。把f1赋给子类引用 s1 即 Son s1 = (Son)f1;
其中 f1 前面的(Son)必须加上,进行强制转换。
一、向上转型。
通俗地讲即是将子类对象转为父类对象。此处父类对象可以是接口。
1、向上转型中的方法调用:
实例
1 public class Animal { 2 3 public void eat() { 4 System.out.println("animal eatting..."); 5 } 6 } 7 8 class Bird extends Animal { 9 10 public void eat() { 11 System.out.println("bird eatting..."); 12 } 13 14 public void fly() { 15 16 System.out.println("bird flying..."); 17 } 18 } 19 20 class Main { 21 public static void doEat(Animal h) { 22 h.eat(); 23 } 24 25 public static void main(String[] args) { 26 27 Animal b = new Bird(); //向上转型 28 b.eat(); 29 //! error: b.fly(); b虽指向子类对象,但此时丢失fly()方法 30 Animail c1 = new Animal(); 31 Bird c2 = new Bird(); 32 doEat(c1); 33 doEat(c2);//此处参数存在向上转型 34 } 35 }