package basic;
public class Cast {
public static void main(String[] args) {
Animal a = new Animal("name a");
Dog d = new Dog("bigYellow","yellow");//见图
Cat c = new Cat("buleCat","bule");
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 Cat );//false
a = new Dog("bigYellow2","yellow2");//这里相当于Animal a = new Dog("bigYellow2","yellow2");见图
System.out.println(a.name);
//System.out.println(a.furcolor); //看不到
System.out.println(a instanceof Animal );//true
System.out.println(a instanceof Dog );//true Animal a = new Dog("bigYellow2","yellow2"); 虽然只看见子类中的父类,但是它还是一个子类的实例,new Dog 就是Dog嘛
//如果想看到furcolor,把Animal a 强制转成 Dog类型
Dog dog1 = (Dog)a;
System.out.println(dog1.furcolor);
}
}
class Animal{
String name;
public Animal(String name) {
this.name = name;
}
}
class Dog extends Animal{
String name;
String furcolor;
public Dog(String name, String furcolor) {
super(name);
this.furcolor = furcolor;
}
}
class Cat extends Animal{
String name;
String eyecolor;
public Cat(String name, String eyecolor) {
super(name);
this.eyecolor = eyecolor;
}
}