Java继承 - 请解释一下 [英] Java inheritance - please explain

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

问题描述

class A {
    public void talk(){
        this.sayIt();
    }

    private void sayIt(){
        System.out.println("class A says...");
    }
}

class B extends A {
    private void sayIt(){
        System.out.println("class B says...");
    }
}

测试类,主要方法:

B b = new B();
b.talk() 

//output
class A says...

我无法得到这个:

B类继承自 A类 ,公共成员并不能看到/继承私有功能。所以在 B类中,我们可以调用 talk() //因为它是由父类继承的。

Class B inherits from class A, the public member and cannot see/inherit the private function. So in class B, we could call talk(). //since it is inherited by the parent class.

现在,在 talk()方法中,是对 sayIt()的调用,因为 sayIt() B类中定义,

Now, in the talk() method, there is a call to sayIt() since sayIt() is defined in class B,

我希望在执行 this.sayIt()时调用 B.sayIt()

this不是指 B类吗?

请解释。

推荐答案

因为你将sayIt()定义为私有,所以B类不能覆盖它。因此,你有两个sayIt()的定义,而不是一个被子类覆盖的定义。

Because you defined sayIt() to be private, class B cannot override it. As such, you have two definitions of sayIt() rather than just one that is overriden by a subclass.

在A类代码的一部分内,它总是会调用A类的版本,即使B类版本受到保护或公开。这是因为A类只知道A类的版本,因为B类版本是覆盖,但却是一种完全不同的方法,恰好可以共享相同的名称。

While inside a section of class A code, it will always call the version from class A, even if the class B version was protected or public. This is because class A only knows about the version from class A since the class B version is not an override, but a completely different method that just so happens to share the same name.

在B类代码的一部分内部,它总是会调用B类的版本,因为A类版本被标记为私有。正如其他人所指出的,如果您将定义更改为受保护或公开,它将在B类中可见,它将执行您想要的操作。

While inside of a section of class B code, it will always call the version from class B since the class A version is marked private. As noted by others, if you change the definition to protected or public, it will be visible to class B and it will do what you want.

请注意,如果您是要使用默认(包)可见性,范围规则将变得非常复杂,实际结果将根据哪个子类在同一个包中以及哪些子类在不同的包中而变化。

Note that if you were to use the default (package) visibility, the scoping rules would get to be very complex and the actual results would vary depending on which subclasses are in the same package and which are in different ones.

这篇关于Java继承 - 请解释一下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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