2010北大青鸟招生简章

Java中对象转换

北京新兴桥中心  2009-11-08
  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);
    }
}

作者: 新兴桥北大青鸟
原载: 北京新兴桥中心  
版权所有,转载时必须以链接形式注明作者和原始出处及本声明
高中生入口-新兴桥北大青鸟
大学生入口-新兴桥北大青鸟
三校生入口-新兴桥北大青鸟
去名企入口-新兴桥北大青鸟

开班时间-新兴桥北大青鸟

新兴桥中心报名咨询
新兴桥北大青鸟地址
邮编
010-63953355 62887070 62887171
北京大学畅春园西300米(海淀公园北门对面)迁址说明
100036京ICP备07002693号