[英]Restricting child class from accessing parent class method
Say I have an interface I and classes A and B. 说我有一个接口I以及类A和B。
interface I
{
method();
}
class A implements I
{
method()
{ //Implementation 1
}
}
class B extends A
{
method()
{ //Implementation 2
}
}
I want to restrict B from accessing 'method'. 我想限制B访问“方法”。 A call to b.method() should always use a.method() instead of b.method implementation where a and b are instances of A and B respectively. 调用b.method()时应始终使用a.method()而不是b.method实现,其中a和b分别是A和B的实例。 Is there any workaround? 有什么解决方法吗?
Wish interfaces supported another access modifier to handle such cases. 希望接口支持另一个访问修饰符来处理这种情况。
As stealthjong alluded to in their comment, you can achieve this by making A
's implementation of method()
final
: 正如Stealthjong在他们的评论中提到的那样,您可以通过将A
的method()
final
:
interface I {
public void method();
}
class A implements I {
public final void method() {
System.out.println("Hello World!");
}
}
class B extends A { }
Because A
applied the final
modifier to the implementation of method()
, B
cannot then redefine it and will instead always call the version that it inherits from A
. 因为A
将final
修饰符应用于method()
的实现,所以B
无法重新定义它,而将始终调用它从A
继承的版本。
If I were to write: 如果我要写:
B instance = new B();
instance.method();
I would see the output "Hello World!"
我将看到输出"Hello World!"
. 。
You can implement B like this: 您可以这样实现B:
class B extends A
{
method()
{
method(true);
}
method(boolean callSuper)
{
if (callSuper)
{
super.method();
} else {
method_impl();
}
method_impl()
{
//Implementation method of B class
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.