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); } }
|