——Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ——-
多态:可以理解为事物存在的多种体现形态。
1.多态的体现
父类的引用指向子类的对象,父类的引用接收子类的对象。
2.多态的前提
类与类之间必须是继承或者实现的关系。通常还有一个前提 就是覆盖
3.多态的好处
大大的提高了程序的扩展性
4.多态的弊端
提高了扩展性,但是只能使用父类的引用访问父类中的成员。
5.多态的应用
6.多态中成员的特点
a)非静态成员函数:在编译时期,参阅引用型变量所属的类中是否有调用的方法。如果有,编译通过,如果没有编译失败。
在运行时期,参阅对象所属的类中是否有调用的方法。
总结,成员函数在多态调用的时候,编译看左边父类,运行看右边子类。
b)成员变量:无论编译和运行,都参考左边父类。
c)静态成员函数:无论编译和运行都参考左边父类。
示例代码:
class DuoTaiDemo1
{
public static void main(String[] args)
{
Cat c = new Cat();
Dog d = new Dog();
method(c);
method(d);
}
public static void method(Animal a)
{
a.eat();
}
}
abstract class Animal
{
abstract void eat();
}
class Dog extends Animal
{
void eat()
{
System.out.println("ken gu tou");
}
void kanjia()
{
System.out.println("kanjia");
}
}
class Cat extends Animal
{
void eat()
{
System.out.println("eat fish");
}
void CatchMouse()
{
System.out.println("Catch mouse");
}
}
结果: