java多态-转型

public class DuoTaiDemo {

	/**
	 * @param args
	 */

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Animal cat = new Cat();
		funtion(cat);
		Cat c = (Cat)cat;
		c.catchmouse();
		
		Animal dog = new Dog();
		funtion(dog);
		
		Animal pig = new Pig();
		funtion(pig);
	}
	public static void funtion(Animal a) {
		a.eat();
		
		if (a instanceof Cat) {
			Cat c = (Cat) a;
			c.catchmouse();
		}
		else if (a instanceof Dog) {
			Dog d = (Dog) a;
		}
		else if (a instanceof Pig) {
			Pig p = (Pig) a;
			p.gongdi();
		}
			
		
	}
}

abstract class Animal{
	abstract void eat();
}
class Cat extends Animal{
	public void eat() {
		System.out.println("鱼");
	}
	
	public void catchmouse() {
		System.out.println("抓老鼠");
	}
}

class Dog extends Animal{
	public void eat() {
		System.out.println("骨头");
	}
}

class Pig extends Animal{
	public void eat() {
		System.out.println("饲料");
	}
	public void gongdi() {
		System.out.println("拱地");
	}
}

你可能感兴趣的:(java多态-转型)