简体   繁体   English

如何在同一个包中隐藏类方法

[英]How to hide a class method within the same package

So I have a package called ABC with class A, class B and class C. Now my main class is outside the package and calls a Class A method called show() which is a public static method.所以我有一个名为 ABC 的包,其中包含 A 类、B 类和 C 类。现在我的主类在包外并调用一个名为 show() 的 A 类方法,它是一个公共静态方法。 Basically Class A acts like a gateway for package ABC.基本上,A 类就像是 ABC 包的网关。 Now I have class C extend class B and I have an abstract method called execute() in class B thats been overridden in class C. Now the access modifier for execute() is protected.现在我有 C 类扩展 B 类,我在 B 类中有一个名为 execute() 的抽象方法,它在 C 类中被覆盖。现在 execute() 的访问修饰符受到保护。 Now I can't access execute() from main which is what I want but I can still access it from Class A because it's inside the same package.现在我无法从 main 访问 execute(),这是我想要的,但我仍然可以从 A 类访问它,因为它在同一个包中。 How can I hide execute inside the same package, ie how do I hide execute() in Class A but still be able to access it in Class C?如何在同一个包中隐藏执行,即如何在 A 类中隐藏 execute() 但仍然能够在 C 类中访问它?

不幸的是,Java 没有相应的可见性修饰符,protected 是 package-private 的超集。

The only way you can hide the execute() from class A is to make it private in class C. But since the execute() is an abstract method in class B, this combination is illegal ( private + abstract ).对 A 类隐藏execute()的唯一方法是在类 C 中将其设为private 。但由于execute()是类 B 中的抽象方法,因此这种组合是非法的( private + abstract )。 Even if you make it protected, you can't override it and make it private in the class B, like in this example:即使您将其设置为受保护,也无法覆盖它并将其设置为 B 类中的private ,如下例所示:

abstract class B 
{
 protected abstract void execute(); 
}

and :和 :

class C
{
 @Override
 private void execute() {} // not working
}

Because it's illegal to assign a weaker access privileges when you override a method.因为在重写方法时分配较弱的访问权限是非法的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM