Java中继承的私有方法 [英] private method in inheritance in Java
问题描述
我对在继承中使用私有方法感到困惑,例如:
I have confusion about using private methods in inheritance, for example:
public class A {
private void say(int number){
System.out.print("A:"+number);
}
}
public class B extends A{
public void say(int number){
System.out.print("Over:"+number);
}
}
public class Tester {
public static void main(String[] args) {
A a=new B();
a.say(12);
}
}
根据以上代码,我我对私有方法的继承感到困惑,是从类A
继承到 B
的私有方法吗?或者两个类中的say方法完全不相关?由于代码在main()方法中运行时出错,似乎 class B
无法从类A $调用私有方法c $ c>。
Based on the codes above, I am confused about the inheritance of private method, is the private method inherited from class A
to B
? Or the say methods in both classes are totally unrelated? As the code has error when it is running in main() method, it seems like class B
cannot invoke the private method from class A
.
推荐答案
如果您希望子类可以访问需要保持<$ c $的超类方法c> private ,然后 protected
是您要查找的关键字。
If you want a subclass to have access to a superclass method that needs to remain private
, then protected
is the keyword you're looking for.
-
私人
只允许包含该成员的班级访问该
会员。 -
受保护的
允许在类中访问该成员,并允许
所有子类。 -
公共
允许任何人访问该会员。
Private
allows only the class containing the member to access that member.Protected
allows the member to be accessed within the class and all of it's subclasses.Public
allows anyone to access the member.
这篇关于Java中继承的私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!