-
public class PolyTest
{
public static void main(String[] args)
{
//Parent parent = new Parent();
//parent.sing();
//Child child = new Child();
//child.sing();
Parent p = new Child();
p.sing();
}
}
class Parent
{
public void sing()
{
System.out.println("parent is singing");
}
}
class Child extends Parent
{
public void sing()
{
System.out.println("child is singing");
}
}
-
public class PolyTest2
{
public static void main(String[] args)
{
//Animal animal = new Animal();
//animal.sing();
//Dog dog = new Dog();
//dog.sing();
//Animal a = new Dog();//父类的引用指向子类的对象
//a.sing();
Animal a = new Dog();
Dog dog = (Dog)a;
dog.sing();
Animal b = new Cat();
Dog dog = (Dog)b;
dog.sing();//可编译,却无法执行。变量b指向Cat()对象
}
}
class Animal
{
public void sing()
{
System.out.println("animal is singing");
}
}
class Dog extends Animal
{
public void sing()
{
System.out.println("dog is singing");
}
}
class Cat extends Animal
{
public void sing()
{
System.out.println("cat is singing");
}
}