一:例子
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的所有属性了。