Java中對象轉換的理解

來源:互聯網
上載者:User

   Java的變數類型之間可以進行轉換,對象之間也可以。

    子類對象轉為父類對象,可以不進行強制轉換,因為子類繼承父類對象。

    但是,當父類對象轉換為子類對象時(若且唯若父類對象本來是由子類預設轉換過去的情況),可以對父類對象進行強制轉換。

public class TestObject {
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Animal a = new Animal();
        Dog d = new Dog("yellow");
        d.name = "bigYellow";
        System.out.println( a.print( d ) );   
    }
}

class Animal{
    String name;
   
    public void setName(String n){
        this.name = n;
    }
   
    public String getName(){
        return this.name;
    }
   
    public String print(Animal a){
        String result = "";
        if (a instanceof Dog) {
            Dog d = (Dog)a;
            result = "Name:" + a.name + "\n" + "FurColor:" + d.furColor;
        }else if (a instanceof Cat) {
            Cat c = (Cat)a;
            result = "Name:" + a.name + "\n" + "EyeColor:" + c.eyeColor;
        }else{
            result = "Name:" + a.name;
        }
        return result;   
    }
}

class Cat extends Animal{
    String eyeColor;
    public void setEyeColor(String e){
        this.eyeColor = e;
    }
    public String getEyeColor(){
        return this.eyeColor;
    }
   
    Cat(String e){
        this.setEyeColor(e);
    }
}

class Dog extends Animal{
    String furColor;
    public void setFurColor(String f){
        this.furColor = f;
    }
    public String getFurColor(){
        return this.furColor;
    }
   
    Dog (String d){
        this.setFurColor(d);
    }
}
 

 96堆棧 軟體編程網,http://www.96dz.com,提供C語言、C++編程、VC++編程、Java編程、C#編程、NET編程、Linux編程、Web編程等全面技術資訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.