继承中的私有方法 [英] Private methods in Inheritance

查看:79
本文介绍了继承中的私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个有趣的代码片段:

Here's an interesting code snippet:

public class Superclass {

    public static void main (String[] args){
        Superclass obj = new Subclass();
        obj.doSomething(); #prints "from Superclass"
    }

    private void doSomething(){System.out.println("from Superclass");}
}

class Subclass extends Superclass {

    private void doSomething(){System.out.println("from Subclass");}

}

我知道子类不会继承其父级的私有成员,但是这里obj设法调用一个它应该没有访问权限的方法。在编译时,obj的类型为Superclass,在运行时类型为Subclass。

I know that subclasses do not inherit the private members of its parent, but here obj manages to call a method to which it should have no access. At compile time obj is of type Superclass, at runtime of type Subclass.

这可能与doSomething()的调用发生在驱动程序类中的事实有关,而驱动程序类恰好是它自己的类(以及它的原因)可以在第一时间调用doSomething()。

This probably has something to do with the fact that the call to doSomething() is taking place inside the driver class, which happens to be its own class (and why it's possible to invoke doSomething() in the first place).

所以问题归结为,obj如何访问其父级的私有成员?

So the question boils down to, how does obj have access to a private member of its parent?

推荐答案

你自己回答了。由于私有方法不是继承的,超类引用会调用自己的私有方法。

You answered it yourself. As the private methods are not inherited, a superclass reference calls its own private method.

这篇关于继承中的私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆