java对象转型体现可扩展性

java对象转型体现可扩展性

public class TestAnimal {
	public static void main(String args[]) {
		TestAnimal t = new TestAnimal();
		Animal a = new Animal("name");
		Cat c = new Cat("catname","blue");
		Dog d = new Dog("dogname","black");
		t.f(a);t.f(c);t.f(d);
	}	
	public void f(Animal a) {
		System.out.println("name: "+a.name);
		if(a instanceof Cat ) {
			Cat cat = (Cat)a;
			System.out.println(" "+cat.eyescolor+" eyes");
		} 
		else if(a instanceof Dog) {
			Dog dog = (Dog)a;
			System.out.println(" "+dog.furcolor+" fur");
		}
	}	
		
		
		
	
}

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

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

class Dog extends Animal {
	public String furcolor;
	Dog(String n,String c) {
		super(n); furcolor = c;
	}
}

 

posted @ 2019-07-30 10:32  水果、、  阅读(301)  评论(0编辑  收藏  举报