向上轉型: 父親 f=new 孩子();
向下轉型:
父親 f=new 孩子2();
孩子2 c=(孩子2)f;//孩子 c=f;這樣是錯誤的,將父類對象直接賦給子類是錯誤的,因為父類對象也不一定是子類的實例。
一個四邊形不一定就是平行四邊形也許是梯形,越是具體的對象具有的特性就越多,越抽象的對象具有的特性越少,在向下轉型操作時,將特性范圍小的對象轉換為特性范圍大的對象時肯定會出問題,所以需要告知編譯器這個對象就是平行四邊形。
將父類對象強制轉換為某個子類對象,這種方式稱為顯式類型轉換。向下轉型時必須使用。
1 class Person{ 2 private String name; 3 private int money; 4 public Person(){ 5 name="Tom"; 6 money=1000; 7 } 8 public Person(String Name,int Money){ 9 name=Name; 10 money=Money; 11 } 12 public void feed(Pet pet){ 13 pet.eat(); 14 if(pet instanceof Dog){ 15 money-=10; 16 }else if(pet instanceof Penguin){ 17 money-=20; 18 } 19 System.out.println("the master's remanent money is "+money); 20 } 21 } 22 class Pet{ 23 protected String name; 24 protected int health; 25 public Pet(){ 26 name="pp"; 27 health=100; 28 } 29 public void eat(){ 30 System.out.println("pet eat"); 31 } 32 } 33 class Dog extends Pet{ 34 public void eat(){ 35 health+=10; 36 System.out.println("dog eat"); 37 } 38 } 39 class Penguin extends Pet{ 40 public void eat(){ 41 health+=20; 42 System.out.println("penguin eat"); 43 } 44 } 45 public class HelloWorld{ 46 public static void main(String args[]){ 47 Person LiMing=new Person("LiMing",2000); 48 Dog d=new Dog(); 49 Penguin p=new Penguin(); 50 LiMing.feed(d); 51 LiMing.feed(p); 52 } 53 }
這個人喂食動物的例子還可以說明一下下
結果是