1.向上类型转换upcast
向下类型转换downcast
public class PolyTest2
{
public static void main(String[] args)
{
/*
Animal animal = new Cat();
Animal animal2 = new Animal();
animal2 = animal;
animal2.sing();
*/
/*
Animal animal = new Cat();
Animal animal2 = new Animal();
animal = animal2;
animal.sing();
*/
/*
Cat cat = new Cat();
Animal animal = cat;
animal.sing();
*/
/*
Animal animal = new Animal();
Cat cat = (Cat)animal;//可编译,不能执行。
*/
//向上类型转换
Cat cat = new Cat();
Animal animal = Cat;
animal.sing();
//向下类型转换
Animal a = new Cat();
Cat cat = (Cat)a;
cat.sing();
}
}
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");
}
}
public class PolyTest3
{
public static void main(String[] args)
{
//Fruit f = new Pear();
//f.run();
//Pear p = (Pear)f;
//p.run();
System.out.println("----------------");
//Fruit f = new Pear();
//f.grow();//无法编译,父类Fruit 没有grow()方法
Fruit f = new Pear();
Pear p = (Pear)f;
p.grow();
}
}
class Fruit
{
public void run()
{
System.out.println("fruit is running");
}
}
class Pear extends Fruit
{
public void run()
{
System.out.println("pear is running");
}
public void grow()
{
System.out.println("pear is growing");
}
}
public class PolyTest4
{
public static void main(String[] args)
{
A a = null;
if(args[0].equals("1"))
{
a = new B();
}
else if(args[0].equals("2"))
{
a = new C();
}
else if(args[0].equals("3"))
{
a = new D();
}
a.method();
}
}
class A
{
public void method()
{
System.out.println("A");
}
}
class B extends A
{
public void method()
{
System.out.println("B");
}
}
class C extends A
{
public void method()
{
System.out.println("C");
}
}
class D extends A
{
public void method()
{
System.out.println("D");
}
}