class Animal{
public String name;
Animal(String name){
this.name = name;
}
}
class Cat extends Animal{
public String eyesColor;
Cat(String name, String eyesColor){
super(name);this.eyesColor = eyesColor;
}
}
class Dog extends Animal{
public String furColor;
Dog(String name, String furColor){
super(name);this.furColor = furColor;
}
}
public class ObjectConvert{
public static void main(String args[]){
Animal a = new Animal("animal");
Cat c = new Cat("catname","blue");
Dog d = new Dog("dogname","black");
/*r instanceof class 返回的是r實際所指的對象是否是class類,r若果是class類以及其子類則返回true*/
System.out.println(a instanceof Animal);//true
System.out.println(c instanceof Animal);//true
System.out.println(d instanceof Animal);//true
System.out.println(a instanceof Cat);//false
a = new Dog("bigyellow","yellow");
System.out.println(a.name);
//System.out.println(a.furColor);//①錯誤,a雖然是指向了Dog對象,但a並看不到Dog繼承父類的部分,看不到Dog新增屬性和方法
//因爲父類對象的引用不能訪問子類新增成員
System.out.println(a instanceof Animal);//true
System.out.println(a instanceof Dog);//true
Dog d1 = (Dog)a;//父類引用給子類引用賦值,必須強制轉換爲子類引用
System.out.println(d1.furColor);
Animal a1 = c;//子類引用給父類引用賦值,可以直接賦值(隱式轉換)也可以強制轉換Animal a1 = (Animal)c;
System.out.println(a1.name);
//System.out.println(a1.eyesColor);//錯誤,同①
}
}
總結:
1.父類引用可以指向子類對象,但是不能再通過父類引用訪問子類新增的成員方法和變量
2.子類引用可以直接賦值給父類引用
3.父類引用如果指向子類對象,則可以用強制轉換將其賦值給子類引用
4.不同的子類引用之間不能相互賦值,也不能強制轉換(轉換顯然是不合理的)