java之對象轉型


對象轉型(casting)

1、一個基類的引用類型變量可以“指向”其子類的對象。

2、一個基類的引用不可以訪問其子類對象新增加的成員(屬性和方法)。

3、可以使用 引用變量 instanceof 類名 來判斷該引用型變量所“指向”的對象是否屬於該類或該類的子類。

4、子類的對象可以當做基類的對象來使用稱作向上轉型(upcasting),反之成為向下轉型(downcasting)。

 

 
         
public class TestCasting{
    public static void main(String args[]){
        Animal a = new Animal("a");
        Cat c = new Cat("c","cEyesColor");
        Dog d = new Dog("d","dForlorColor");
        
        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 Dog);        //false
        
        a = new Dog("d2","d2ForlorColor");        //父類引用指向子類對象,向上轉型
        System.out.println(a.name);                //可以訪問
        //System.out.println(a.folorColor);   //!error   不可以訪問超出Animal自身的任何屬性
        System.out.println(a instanceof Animal);    //是一只動物
        System.out.println(a instanceof Dog);        //是一只狗,但是不能訪問狗里面的屬性
        
        Dog d2 = (Dog)a;    //強制轉換
        System.out.println(d2.folorColor);    //將a強制轉換之后,就可以訪問狗里面的屬性了
    }
}
class Animal{
    public String name;
    public Animal(String name){
        this.name = name;
    }
}
class Dog extends Animal{
    public String folorColor;
    public Dog(String name,String folorColor){
        super(name);
        this.folorColor = folorColor;
    }
}
class Cat extends Animal{
    public String eyesColor;
    public Cat(String name,String eyesColor){
        super(name);
        this.eyesColor = eyesColor;
    }
}
 
         

 

 

運行結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM