且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java继承 - 请解释一下

更新时间:2023-11-09 23:21:52

因为你将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.