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