JavaSE基础之多态中成员的访问

当一个父类引用持有子类对象时,对于成员(变量及方法)的访问是有不同的,具体如下:

public class MainClass {
    public static void main(String[] args) {
        Father f = new Child();
        System.out.println(f.num);
        f.hello();
    }
}

public class Father {
    int num = 10;

    public void hello(){
        System.out.println("Hello, I'm father class");
    }
}

public class Child extends Father {
    int num = 20;

    public void hello() {
        System.out.println("Hello, I'm child class");
    }
}

一、成员变量

f.num的输出结果是10

因为在child对象中,会有专门的一块空间来存储父类的数据,父类引用访问成员变量只能访问到这片空间。

Child对象

当我们使用Child child = new Child();来创建对象时,child.num就访问的是this中的num

总结:父类引用访问变量,编译看左边(父类),运行看左边(父类)。

二、 成员方法

f.hello();方法调用输出结果是Hello, I'm child class

虽然在编译时,f仍然只能看见super的空间,但是在程序运行时,f调用的确是子类的hello()方法,这也叫做动态绑定。

总结:父类引用访问方法,编译看左边(父类),运行看右边(父类)。

以上是以前的知识点加深记忆,所以并没有写的很全面。

你可能感兴趣的:(JavaSE基础之多态中成员的访问)