[英]How to access a protected method of superclass in a subclass?
I have parent-child classes in two different packages. 我在两个不同的包中有父子类。 I am overriding a method of protected type. 我覆盖了一种保护类型的方法。 I want to access super class protected method in subclass. 我想在子类中访问受超类保护的方法。
Consider below code: 考虑下面的代码:
package package1;
public class Super
{
protected void demoMethod()
{
System.out.println("In super method");
}
}
package package2;
import package1.Super;
public class Sub extends Super
{
@Override
protected void demoMethod()
{
System.out.println("In sub method");
}
public static void main(String[] args)
{
//code for accessing superclass demoMethod to print "In super method"
}
}
In the main method of sub class, I want to access super class demoMethod
which prints "In super method". 在子类的主方法中,我要访问打印“ In super method”的超类demoMethod
。 I know demoMethod
won't be visible from sub class using super class object reference to call demoMethod
. 我知道demoMethod
不会使用超类对象引用调用子类可见demoMethod
。
Is it possible or not? 有没有可能? If yes, how? 如果是,怎么办?
Consider me new to Java and provide answers replacing comment in main method. 以Java为新手,并提供替换主要方法中的注释的答案。
在子类中使用super.demoMethod()
或将其从子类中完全删除
Your main() method cannot access the superclass implementation of demoMethod()
-- because it's overridden in the child class. 您的main()方法无法访问demoMethod()
的超类实现-因为它在子类中被覆盖。
Your main() method can access demoMethod()
, through a reference of the subclass type, even though it's protected, because it's in the same package as your subclass. 您的main()方法可以通过子类类型的引用访问 demoMethod()
,即使它是受保护的,因为它与您的子类位于同一包中。 But it will call the subclass implementation. 但是它将调用子类实现。
But if you're "using superclass object reference to call demoMethod", the method will not be accessible, and your code will not compile. 但是,如果您“使用超类对象引用来调用demoMethod”,则该方法将不可访问,并且您的代码将无法编译。 Your superclass is in a different package. 您的超类在另一个包中。 Methods marked protected
can only be accessed by subclasses and by code in the same package. 标记为protected
方法只能由子类和同一包中的代码访问。
If you made the method public
in both subclass and superclass, calling demoMethod()
would call the subclass implementation, regardless whether the reference was of the super or subclass type. 如果在子类和超类中都public
了该方法,则无论引用是demoMethod()
类还是子类类型,调用demoMethod()
都会调用子类实现。
An instance of the subclass can call super.demoMethod()
as part of the implementation of its methods. 子类的实例可以调用super.demoMethod()
作为其方法的实现的一部分。 But the main() method cannot. 但是main()方法不能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.