JAVA-多态

引入:

    Animal a = new Dog();

    对象a具有两种类型:

    编译类型:声明对象的类型Animal。

    运行类型:对象的实际类型Dog。

    编译类型必须是运行类型的父类/或相同。

多态就是对象具有多种形态,对象可以存在不同的形式。

    Animal a = null;

    a = new Dog();    //此时a是Dog类型的形态。

    a = new Cat();    //此时a是Cat类型的形态。

多态的前提:可以是继承关系(类和类),也可以是实现关系(接口和实现类)。

//多态演示
class Animal
{
	public void eat()
	{
		System.out.println("吃东西");
	}
}

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

class Cat extends Animal
{
	public void eat()
	{
		System.out.println("猫吃鱼");
	}
}
public class AnimalDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//没有多态
		Dog d = new Dog();
		d.eat();
		Cat c = new Cat();
		c.eat();
		System.out.println("-------------------------------");
		//存在多态
		Animal a = new Dog();
		a.eat();
		a = new Cat();
		a.eat();
	}

}
狗吃骨头
猫吃鱼
-------------------------------
狗吃骨头
猫吃鱼


猜你喜欢

转载自blog.csdn.net/tommy5553/article/details/80771294