[java]代码库
public class TestCasting{
public static void main(String args[]){
Animal a = new Animal("a");
Cat c = new Cat("c","cEyesColor");
Dog d = new Dog("d","dForlorColor");
System.out.println(a instanceof Animal); //true
System.out.println(c instanceof Animal); //true
System.out.println(d instanceof Animal); //true
System.out.println(a instanceof Dog); //false
a = new Dog("d2","d2ForlorColor"); //父类引用指向子类对象,向上转型
System.out.println(a.name); //可以访问
//System.out.println(a.folorColor); //!error 不可以访问超出Animal自身的任何属性
System.out.println(a instanceof Animal); //是一只动物
System.out.println(a instanceof Dog); //是一只狗,但是不能访问狗里面的属性
Dog d2 = (Dog)a; //强制转换
System.out.println(d2.folorColor); //将a强制转换之后,就可以访问狗里面的属性了
}
}
class Animal{
public String name;
public Animal(String name){
this.name = name;
}
}
class Dog extends Animal{
public String folorColor;
public Dog(String name,String folorColor){
super(name);
this.folorColor = folorColor;
}
}
class Cat extends Animal{
public String eyesColor;
public Cat(String name,String eyesColor){
super(name);
this.eyesColor = eyesColor;
}
}
初级程序员
by: 永远的希望 发表于:2016-07-06 14:23:45 顶(0) | 踩(0) 回复
谢谢分享
回复评论