您的位置:首页 > 编程语言 > Java开发

java例程练习(对象转型及instanceof关键字)

2012-04-22 14:07 507 查看
public class Test {
public static void main(String[] args) {
Animal a = new Animal("name");
Cat c = new Cat("Tom", "Blue");
Dog d = new Dog("Pipi", "Black");

System.out.println(a instanceof Animal);
System.out.println(c instanceof Animal);
System.out.println(d instanceof Animal);
System.out.println(a instanceof Cat);
System.out.println();

a = new Dog("Bangbang", "Yellow");
System.out.println(a instanceof Animal);
System.out.println(a instanceof Dog);
System.out.println();

Dog d1 = (Dog)a;
System.out.println(d1 instanceof Animal);
System.out.println(d1 instanceof Dog);
System.out.println();

Test test = new Test();
test.info(a);
test.info(c);
test.info(d);
test.info(d1);
}

public void info(Animal	a) {
System.out.print("" + a.name);
if(a instanceof Cat) {
Cat cat = (Cat)a;
System.out.print(" has " + cat.eyeColor + " eyes");
} else if(a instanceof Dog) {
Dog dog = (Dog)a;
System.out.print(" has " + dog.furColor + " fur");
}
System.out.println();
}

}

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

class Cat extends Animal {
public String eyeColor;
Cat(String n, String c) {
super(n);
eyeColor = c;
}
}

class Dog extends Animal {
public String furColor;
Dog(String n, String c) {
super(n);
furColor = c;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: