是否可以在 Java 中隐藏或降低对继承方法的访问权限?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1902195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to hide or lower access to Inherited Methods in Java?
提问by Daniel Bingham
I have a class structure where I would like some methods in a base class to be accessible from classes derived directly from the base class, but not classes derived from derived classes. According to the Java Language specification it is possible to override access specifications on inherited methods to make them more public, but not more private. For example, this is the gist of what I need to do, but is illegal:
我有一个类结构,我希望基类中的某些方法可以从直接从基类派生的类中访问,但不能从派生类派生的类中访问。根据 Java 语言规范,可以覆盖对继承方法的访问规范,使它们更公开,但不是更私密。例如,这是我需要做的事情的要点,但这是非法的:
// Defines myMethod
public class Base {
protected void myMethod() {}
}
// Uses myMethod and then hides it.
public class DerivedOne extends Base {
@Override
private void myMethod();
}
// can't access myMethod.
public class DerivedTwo extends DerivedOne {
}
Is there any way to accomplish this?
有什么办法可以做到这一点吗?
Edited to explain why I would like to do this:
编辑以解释为什么我想这样做:
In this case the class structure is a data handling and import structure. It reads in and parses text files full of tabular data and then stores them in a database.
在这种情况下,类结构是数据处理和导入结构。它读入并解析充满表格数据的文本文件,然后将它们存储在数据库中。
The base class is the base table class managing the database handling part of it. There is a fair amount of functionality contained in it that is common to all table types - as once they are in the database they become uniform.
基类是管理它的数据库处理部分的基表类。其中包含相当多的功能,这些功能对所有表类型都是通用的——因为一旦它们在数据库中,它们就会变得统一。
The middle class is specific to the kind of table in the file being parsed, and has the table parsing and import logic. It needs access to some of the base class's database access functions.
中间类特定于被解析文件中的表类型,具有表解析和导入逻辑。它需要访问一些基类的数据库访问函数。
The top level class is specific to the table and does nothing more than initialize the table's layout in a way the parent classes can understand. Also users of the base class do not need to see or access the database specific functions which the middle class do. In essence, I want to reveal these functions only to one level above the base class and no one else.
顶级类特定于表,只是以父类可以理解的方式初始化表的布局。此外,基类的用户不需要查看或访问中间类所做的数据库特定功能。从本质上讲,我只想在基类之上的一级而不是其他任何级别上显示这些功能。
I ask because, although the code I posted as an example is illegal, there may be some other means to accomplish the same end. I'm asking if there is.
我问是因为,虽然我作为示例发布的代码是非法的,但可能还有其他一些方法可以达到同样的目的。我问有没有
Perhaps hiding is the wrong way to phrase this - what I really need to do is expose some functionality that should be private to the base class to the class one level up in the hierarchy. Hiding would accomplish this - but I can see how hiding would be a problem. Is there another way to do this?
也许隐藏是错误的表述方式——我真正需要做的是向层次结构中的上一级类公开一些应该是基类私有的功能。隐藏可以实现这一点 - 但我可以看到隐藏将是一个问题。有没有其他方法可以做到这一点?
回答by Dave Sims
I think the very nature of the problem as you've posed it exposes conceptual problems with your object model. You are trying to describe various separate responsibilities as "is a" relationships when actually what you should be doing is describing "has a" or "uses a" relationships. The very fact that you want to hide base class functionality from a child class tells me this problem doesn't actually map onto a three-tiered inheritance tree.
我认为您提出的问题的本质暴露了您的对象模型的概念问题。您试图将各种不同的职责描述为“是一个”关系,而实际上您应该做的是描述“有一个”或“使用一个”的关系。您想对子类隐藏基类功能这一事实告诉我这个问题实际上并没有映射到三层继承树上。
It sounds like you're describing a classic ORM problem. Let's look at this again and see if we can re-map it onto other concepts than strict "is a" inheritance, because I really think your problem isn't technical, it's conceptual:
听起来你在描述一个经典的 ORM 问题。让我们再看看这个,看看我们是否可以将它重新映射到严格的“是”继承之外的其他概念上,因为我真的认为您的问题不是技术问题,而是概念问题:
You said:
你说:
The base class is the base table class managing the database handling part of it. There is a fair amount of functionality contained in it that is common to all table types - as once they are in the database they become uniform.
基类是管理它的数据库处理部分的基表类。其中包含相当多的功能,这些功能对所有表类型都是通用的——因为一旦它们在数据库中,它们就会变得统一。
This could be more clear, but it sounds like we have one class that needs to manage the DB connection and common db operations. Following Single Responsibility, I think we're done here. You don't need to extendthis class, you need to handit to a class that needs to use its functionality.
这可能更清楚,但听起来我们有一个类需要管理数据库连接和常见的数据库操作。遵循Single Responsibility,我想我们到此为止了。你并不需要扩展这个类,你需要用手它的一类需要使用它的功能。
The middle class is specific to the kind of table in the file being parsed, and has the table parsing and import logic. It needs access to some of the base class's database access functions.
中间类特定于被解析文件中的表类型,具有表解析和导入逻辑。它需要访问一些基类的数据库访问函数。
The "middle class" here sounds a bit like a Data Mapper. This class doesn't need to extendthe previous class, it needs to own a reference to it, perhaps injected on the constructor or a setter as an interface.
这里的“中产阶级”听起来有点像Data Mapper。这个类不需要扩展前一个类,它需要拥有对它的引用,可能注入到构造函数或 setter 作为接口。
The top level class is specific to the table and does nothing more than initialize the table's layout in a way the parent classes can understand. Also users of the base class do not need to see or access the database specific functions which the middle class do. In essence, I want to reveal these functions only to one level above the base class and no one else.
顶级类特定于表,只是以父类可以理解的方式初始化表的布局。此外,基类的用户不需要查看或访问中间类所做的数据库特定功能。从本质上讲,我只想在基类之上的一级而不是其他任何级别上显示这些功能。
I'm not clear why a high-level class seems to have knowledge of the db schema (at least that's what the phrase "initialize the table's layout" suggests to me), but again, if the relationship between the first two classes were encapsulation ("has a"/"uses a") instead of inheritance ("is a"), I don't think this would be a problem.
我不清楚为什么高级类似乎了解 db 模式(至少这就是“初始化表的布局”这句话对我的暗示),但同样,如果前两个类之间的关系是封装("has a"/"uses a") 而不是继承 ("is a"),我认为这不是问题。
回答by Jonathan Feinberg
No. I'm not sure why you'd quote the spec and then ask if there's any way to do the opposite of what the spec says...
不。我不确定你为什么要引用规范,然后问是否有任何方法可以做与规范所说的相反的事情......
Perhaps if you explain whyyou want to do this, you could get some suggestions on how.
也许如果您解释了为什么要这样做,您可以获得一些关于如何.
回答by andandandand
When overriding a method you can only make it more public, not more private. I don't know why you use the word "general"
当覆盖一个方法时,你只能让它更公开,而不是更私密。我不知道你为什么用“将军”这个词
Remember that, ordering from least to most restrictive:
请记住,从最少到最严格的顺序:
public<protected<default<private
Yes, "protected" is a less restrictive access modifier than default(when no modifier is used), so you can override a default method marking the overriding method as protected, but not do the opposite.
是的,“ protected” 是比default(未使用修饰符时)限制性更小的访问修饰符,因此您可以覆盖将覆盖方法标记为 的默认方法protected,但不能反其道而行之。
Can:You can override a protectedmethod with a publicone.
Can:你可以用一个protected方法覆盖一个方法public。
Can't:You can't override a publicmethod with a protectedone.
不能:你不能用一个public方法覆盖一个方法protected。
回答by KernelJ
If you did this then DerivedOne would not be a Base, from the DerivedTwo's point of view. Instead what you want is a wrapper class
如果您这样做,那么从 DerivedTwo 的角度来看,DerivedOne 将不是 Base。相反,你想要的是一个包装类
//Uses myMethod but keeps it hidden
public class HiddenBase {
private final Base base = new Base();
private void myMethod();
public void otherMethod() {base.otherMethod();}
}
You can't access protected methods of the base though this way...
通过这种方式,您无法访问基础的受保护方法......
回答by rsp
What you describe comes close to what the protectedaccess class is for, derived classes can access, all others cannot.
您描述的内容接近protected访问类的用途,派生类可以访问,所有其他类都不能。
If you inherit from base classes you have no control over this might pose a problem, you can make the method inaccesible to others by throwing an exception while making the inherited code available to your classes by calling super directly, something like:
如果您从基类继承,您无法控制这可能会造成问题,您可以通过抛出异常使其他人无法访问该方法,同时通过直接调用 super 使继承的代码可用于您的类,例如:
// Uses myMethod and then hides it.
public class DerivedOne extends Base {
@Override
public void myMethod() {
throw new IllegalStateException("Illegal access to myMethod");
}
private void myPrivateMethod() {
super.myMethod();
}
}
Edit: to answer your elaboration, if I understand you correctly you need to specify behaviour in the context of the base class which is defined in the middle class. Abstract protected methods won't be invisible to the classes deriving from the middle class.
编辑:为了回答您的详细说明,如果我理解正确,您需要在中类定义的基类的上下文中指定行为。抽象受保护的方法对于从中类派生的类不会是不可见的。
One possible approach is to define an interface with the methods you would need to be abstract in the base class, keeping a private final reference in the base class and providing a reference to the implementation when constructing the middle class objects.
一种可能的方法是定义一个接口,其中包含您需要在基类中抽象的方法,在基类中保留私有最终引用,并在构造中间类对象时提供对实现的引用。
The interface would be implemented in a (static?) nested inside the middle class. What I mean looks like:
该接口将在嵌套在中间类中的(静态?)中实现。我的意思看起来像:
public interface Specific {
public void doSomething();
}
public class Base {
private final Specific specificImpl;
protected Base(Specific s) {
specificImpl = s;
}
public void doAlot() {
// ...
specificImpl.doSomething();
// ...
}
}
public class Middle extends Base {
public Middle() {
super(new Impl());
}
private Impl implements Specific {
public void doSomething() {
System.out.println("something done");
}
}
}
public class Derived extends Middle {
// Access to doAlot()
// No access to doSomething()
}
回答by extraneon
Inheritance works because everywhere you can use the base class, you can also use one of it's subclasses. The behavior may be different, but the API is not. The concept is known as the Liskov substitution principle.
继承之所以有效,是因为您可以在任何可以使用基类的地方,也可以使用它的子类之一。行为可能会有所不同,但 API 不会。这个概念被称为Liskov 替换原则。
If you were able to restrict access to methods, the resulting class would not have the same API and you would not be able to use substitute an instance of the base class for one of the derived classes, negating the advantage of inheritance.
如果您能够限制对方法的访问,则生成的类将不会具有相同的 API,并且您将无法使用基类的实例替换派生类之一,从而否定继承的优势。
What you actually want to accomplish can be done with interfaces:
你真正想要完成的事情可以通过接口来完成:
interface IBase1 {
}
class Derived1 implements IBase1 {
public void myMethod() {
}
}
class Derived2 implements IBase1 {
}
class UseMe {
public void foo(IBase1 something) {
// Can take both Derived1 and Derived2
// Can not call something.myMethod()
}
public void foo(Derived1 something) {
something.myMethod();
}
public void foo(Derived2 something) {
// not something.myMethod()
}
}
回答by vkraemer
It is possible, but requires a bit of package manipulation and may lead to a structure that is a bit more complex than you would like to work with over the long haul.
这是可能的,但需要对包进行一些操作,并且可能会导致结构比您希望长期使用的结构复杂一些。
consider the following:
考虑以下:
package a;
public class Base {
void myMethod() {
System.out.println("a");
}
}
package a;
public class DerivedOne extends Base {
@Override
void myMethod() {
System.out.println("b");
}
}
package b;
public class DerivedTwo extends a.DerivedOne {
public static void main(String... args) {
myMethod(); // this does not compile...
}
}
I would recommend being nice to yourself, your co-workers and any other person that ends up having to maintain your code; rethink your classes and interfaces to avoid this.
我建议对你自己、你的同事和任何其他最终不得不维护你的代码的人好一点;重新考虑您的类和接口以避免这种情况。
回答by Tushar Thakar
you have to make method final when override it
你必须在覆盖它时使方法最终
public class Base {
protected void myMethod() {}
}
// Uses myMethod and then hides it.
public class DerivedOne extends Base {
@Override
final protected void myMethod(); //make the method final
}
public class DerivedTwo extends DerivedOne {
// can't access myMethod here.
}

