------- android培训、java培训、期待与您交流! ----------
多态是事物存在的多种体现形态,多态作为面向对象的3大特性之一是非常重要的。
多态的体现
父类引用指向了自己的子类对象
Animal a = new Cat();//向上转型
//Animal是Cat的父类
多态提高了程序的扩展性,但只能使用父类的引用访问父类中的成员(很重要)
//还是上面的例子,Animal是父类具有run方法,Cat是子类有catch这个特有方法
Animal a = new Cat();
a.run();
//a.catch();此方法为子类特有访问不了
Cat c = (Cat)a;//将父类引用(子类对象)转成子类类型
c.catch();
注意:不可将父类对象转成子类类型,多态始终是子类对象在变化!
多态中成员函数的特点(非静态)
编译时,看引用型变量所属的类是否有调用的方法,若有则通过,否则编译失败。
运行时,看对象所属的类中是否有调用的方法。
(也就是编译看左边,运行看右边~)
多态中成员变量,静态成员函数的特点
无论编译还是运行,都看左边(引用型变量所属的类)
class Fu
{
int num = 5;
void method1()
{
System.out.println("fu method_1");
}
void method2()
{
System.out.println("fu method_2");
}
static void method4()
{
System.out.println("fu method_4");
}
}
class Zi extends Fu
{
int num = 62;
void method1()
{
System.out.println("zi method_1");
}
void method3()
{
System.out.println("zi method_3");
}
static void method4()
{
System.out.println("zi method_4");
}
}
class Demo
{
public static void main(String[] args)
{
Fu f = new Zi();
System.out.println(f.num);//父类的num
Zi z = new Zi();
System.out.println(z.num);//子类的num
f.method1();//运行子类的方法
f.method2();//运行,子类继承了该方法
//f.method3();//出错父类没有该方法
f.method4();//运行父类的方法
z.method4();//运行子类的方法
}
}