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();//可編譯诉探,卻無法執(zhí)行。變量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");
}
}