java基礎:型別轉換cast

十五樓亮哥發表於2015-02-01

一:例子

public class Animal {
	private String name;
	
	public Animal(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	

}

public class Dog extends Animal{
	private String furColor;
	public Dog(String name,String furColor) {
		super(name);
		this.furColor = furColor;
	}


	public String getFurColor() {
		return furColor;
	}

	public void setFurColor(String furColor) {
		this.furColor = furColor;
	}
	

}

public class Test {
	public static void main(String[] args) {
		
     	//Dog d = new Dog("Hachi1","gray");
		//System.out.println(d instanceof Animal);
		
		
		Animal a = new Dog("Hachi","yellow");
		System.out.println(a.getName());
		//System.out.println(a2.getFurColor()); error
		System.out.println(a instanceof Dog);
		
		Dog d = (Dog) a;
		System.out.println(d.getFurColor()); 


	}

}

輸出結果:

Hachi
true
yellow


二:分析

Animal a = new Dog("Hachi","yellow");

棧空間中建立引用a,指向堆中new出來的子物件Dog("Hachi","yellow");

a的實質就是一隻Dog,a instanceof Dog返回True

但是a只能訪問到Animal的屬性。不能訪問Dog的furColor屬性

只有Dog d = (Dog) a;

另外建立一個引用d,將a強轉成Dog型別,就能訪問Dog的所有屬性了。





相關文章