
面向对象语言中的类有三个特征,封装、继承、多态。封装与继承很好理解,那什么是多态呢?
1.什么是多态?
多态的定义:指允许不同类的对象对同一消息做出响应。即同一消息可以根据发送对象的不同而采用多种不同的行为方式。(发送消息就是函数调用)
简单点解释就是:父类对象的引用指向子类的对象的实例,这样父类在调用方法时可能产生不同的效果!
2.多态实例
abstract class Animal
{
abstract void eat();
}
class Dog extends Animal
{
void eat()
{
System.out.println("狗吃肉!");
}
}
class Cat extends Animal
{
void eat()
{
System.out.println("猫吃鱼!");
}
} class DuoTaiDemo
{
public static void main(String[] args)
{
Animal al=null; al=new Dog();
al.eat(); System.out.println("------------------------"); al=new Cat();
al.eat();
}
}
代码输出:
3. 多态的调用
有如下代码:
class Fu
{
int num = 2;
void show()
{
System.out.println("fu show run");
} static void method()
{
System.out.println("fu static method run");
}
}
class Zi extends Fu
{
int num = 8;
void show()
{
System.out.println("Zi show run");
}
static void method()
{
System.out.println("zi static method run");
}
}
3.1 多态中的成员变量调用
多态调用时,对于成员变量,无论是编译还是运行,结果只参考引用型变量所属的类中的成员变量。
简单说:编译和运行都看左边。
如下代码:
public static void main(String[] args)
{
//演示成员变量。
Fu f = new Zi();
System.out.println(f.num);//
Zi z = (Zi)f;
System.out.println(z.num);//
}
输出:
2
8
3.2 多态中的成员函数调用
多态调用时,对于成员函数,
编译时,参考引用型变量所属的类中是否有被调用的方法。有,编译通过,没有编译失败。
运行时,参考的是对象所属的类中是否有调用的方法。
简单说:编译看左边,运行看右边
public static void main(String[] args)
{
//演示成员方法。 Fu f = new Zi();
f.show();
}
输出:
Zi show run
3.3 多态中的成员函数调用
简单说:编译和运行都看左边。
public static void main(String[] args)
{
//演示静态方法。
Fu f = new Zi();
f.method();
Zi z = (Zi)f;
z.method(); //其实可以像下面这样调用
//Fu.method();
//Zi.method();
}
输出:
fu static method run
zi static method run