保护超类方法免受子类方法的影响
一个类是否有可能有一个只能由其对象调用并对于子类对象隐藏的方法?例如:
class ClassOne {
... // attributes
public void doSomething() { ... }
}
class ClassTwo extends ClassOne {
... // attributes and methods
}
ClassOne c1 = new ClassOne();
c1.doSomething(); // ok to call
ClassTwo c2 = new ClassTwo();
c2.doSomething(); // forbidden
我知道这在继承方面似乎很奇怪,但有可能吗?
PS:本题的目的只是为了了解更多有关 OO 编程的继承的知识。
Is it possible to a class has a method that can only be called by it's objects and hidden for a subclass object? For instance:
class ClassOne {
... // attributes
public void doSomething() { ... }
}
class ClassTwo extends ClassOne {
... // attributes and methods
}
ClassOne c1 = new ClassOne();
c1.doSomething(); // ok to call
ClassTwo c2 = new ClassTwo();
c2.doSomething(); // forbidden
I know this seems weird thinking in therms of inheritance, but is it possible?
PS: the objective of this question is just to learn more about inheritance of OO programming.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是不可能的,也是你的权利,这会破坏继承权。想想
这必须起作用,因为 ClassTwo 是一个 ClassOne。编辑:至少必须编译,如果该方法被重写并执行其他操作取决于您的设计。但你不能让编译器就此产生错误。
It's not possible and your right that this would break inheritance. Think about
This has to work because ClassTwo is a ClassOne. Edit: at least is has to compile, if the method is overridden and does something else is up to your design. But you cannot make the compiler produce an error on this.
由于 doSomething 是在 classOne 中声明的,因此它将在任何子类中可用。您无法隐藏它或降低它的可见性(将其设置为私有或受保护)。由于 ClassTwo 是 ClassOne 的一个,因此它可以完成 ClassOne 可以做的所有事情。
你能得到的最接近的是类似 :
的东西,它并不能完全满足你的要求。
如果您处于需要这样做的情况,最好可能是重新考虑类层次结构,将其划分为具有 doSomething 方法的类类型和不具有 doSomething 方法的类型
,或者将 doSomething 放入接口中。
Since doSomething is declared in classOne it will be available in any subclasses. You can't hide it or reduce it's visibility ( make it private or protected ). Since ClassTwo is a ClassOne it can do everything ClassOne can do.
The closest you can come is something like :
which doesn't quite do what you want.
If you're in a situation where you need to do this best is probably to rethink the class hierarchy into types of your class that have the doSomething method and types that don't
or put doSomething in an interface.
可能我误解了你,但你为什么不把你的方法设为私有或包可见呢?
May be I misunderstood you, but why don't you just make your method private or package visible?