转自:http://www.cnblogs.com/happyframework/p/3332243.html,非常感谢啊
public class test { /** * @param args */ public static void main(String[] args) { printAnimal(new Animal()); printAnimal(new Dog()); } private static void printAnimal(Animal animal) { if(animal instanceof Dog){ System.out.println("I am a " + (Dog) animal); } else { System.out.println("I am an " + animal); } } } class Animal { public String toString() { return "Animal"; } } class Dog extends Animal { public String toString() { return "Dog"; } }