java基础案例:多态的简述


/*
对象的多态性:
动物 x = new 猫();    
猫这类事物既具备了猫的形态,又具备着动物的形态。
这就是对象的多态。
简单说:就是一个对象对应着不同类型。

多态在代码中的体现:
父类或者接口的引用指向其子类的对象。

多态的好处:
提高了代码的扩展性,前期定义的代码可以使用后期的内容

多态的弊端:
1、前期定义的内容不能使用(调用)后期子类的特有内容。

多态的前提:
1、必须有关系,继承,实现。
2、要有覆盖
*/

public class DuoTaiDemo
{
public static void main(String[] args)
{
/*
Dog d = new Dog();
Cat c = new Cat();
method(d);
method(c);
*/

Animal a = new Cat(); //自动类型提升,猫对象提升到了动物类型
Animal a1 = new Dog();
//a.eat();                //作用就是限制对象特有功能的访问。专业讲:向上转型

method(a1);

//如果还想用具体动物的特有功能。
//你还可以将该对象进行向下转型。
//Cat c = (Cat)a;     //这是向下转型
//c.catchMouse();
}

public static void method(Animal a)
{
a.eat();
if(a instanceof Cat)      //instanceof:用于判断对象的具体类型。只能用于引用数据类型判断。
{  //通常在向下转型前用于健壮性判断
Cat c = (Cat)a;
c.catchMouse();
}
else if(a instanceof Dog)
{
Dog d = (Dog)a;
d.lookHome();
}
}
}

abstract class Animal
{
abstract void eat();
}

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

public void lookHome()
{
System.out.println("看家");
}
}

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

public void catchMouse()
{
System.out.println("抓老鼠");
}
}

猜你喜欢

转载自blog.csdn.net/z1888202/article/details/79394672