java多态 成员访问特点(父类引用指向子类对象)

>父类 子类 

package com.dareway.demo;

public class Father {
	public String index="fatherLogo";
	public Father() {
		System.out.println("father creat");
	}
	public void Fly() {
		System.out.println("father Fly");
	}
	public static void eat(){
		System.out.println("father eat");
	}
}
package com.dareway.demo;

public class Son extends Father {
	public String index="sonLogo";
	public String school="qinghua";
	public Son() {
		System.out.println("son creat"+"---"+index);
	}
    public void Fly(){
    	System.out.println("son Fly");
    }
    public static void eat(){
		System.out.println("son eat");
	}
	public static void main(String[] args) {
		Father father=new Son();
		System.out.println(father.index);
		father.Fly();
		father.eat();
		System.out.println("-----------------------------");
		Son faAsSon=(Son)father;
		System.out.println(faAsSon.index);
		System.out.println(faAsSon.school);
		faAsSon.Fly();
		faAsSon.eat();
	}	
}

运行结果:

father creat
son creat---sonLogo
fatherLogo
son Fly
father eat
-----------------------------
sonLogo
qinghua
son Fly
son eat

>总结

多态前提:

 -  要有继承关系。

 -  要有方法重写。

 -  要有父类引用指向子类对象。

1、成员变量:编译看左边(父类),运行看左边(父类)

2、成员方法:编译看左边(父类),运行看右边(子类),动态绑定

3、静态方法:编译看左边(父类),运行看左边(父类)

解释:Animal c = new Cat(); 左边是 Animal 类(或接口) 右边是 Cat()类; 在编译的时候编译器不管你右边是什么类,只要左边的Animal类(或接口)能编译通过就不会报错。但是运行的时候就要按照右边的Cat()类实际情况来运行。

其中,能编译通过的意思:如 c.eat(); ,只要父类中有这个eat方法 ,编译就会通过,但具体执行的时候,如果eat是成员方法,会根据右边子类覆盖的方法进行执行。 

注:

 -  静态方法和类相关,算不上重写,所以,访问还是左边的(父类)

 -  只有非静态的成员方法,编译看左边,运行看右边

 -  虚拟机编译的时候看的是父类,所以多态有一个弊端:不能使用子类特有的属性和方法。必须向下转型之后才可以调用。

猜你喜欢

转载自blog.csdn.net/AhaQianxun/article/details/94717561