Java 隐藏:客户端类有什么方法可以调用“super”?
除了在子类上显式添加一个方法来调用 super 方法之外,还有什么办法可以暂时“取消隐藏”它吗?我想在 Test2
实例上调用 super.blah()
方法。我必须使用像 originalBlah
这样的方法,还是有其他方法?
public class TestingHiding {
public static void main(String[] args) {
Test1 b = new Test2();
b.blah();
}
}
class Test2 extends Test1 {
public void blah() {
System.out.println("test2 says blah");
}
public void originalBlah() {
super.blah();
}
}
class Test1 {
public void blah() {
System.out.println("test1 says blah");
}
}
编辑:抱歉在游戏后期添加问题,但我有一个内存闪存(我认为):在 C# 中这有什么不同吗?这取决于您认为
您拥有哪个类(Test1 或 Test2)?
Aside from adding a method explicitly on the subclass to call a super
method, is there anyway to "unhide" it temporarily? I would like to call the super.blah()
method on a Test2
instance. Must I use a method like originalBlah
, or is there another way?
public class TestingHiding {
public static void main(String[] args) {
Test1 b = new Test2();
b.blah();
}
}
class Test2 extends Test1 {
public void blah() {
System.out.println("test2 says blah");
}
public void originalBlah() {
super.blah();
}
}
class Test1 {
public void blah() {
System.out.println("test1 says blah");
}
}
Edit: Sorry to add to the question late in the game, but I had a memory flash (I think): in C# is this different? That it depends on which class you think
you have (Test1 or Test2)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
据我了解,您想做类似
Test1 b = new Test2(); 的事情b.super.blah()。这是不可能的,super 严格限制为从子类内部调用超类。
As I understand you want to do something like
Test1 b = new Test2(); b.super.blah()
. This cannot be done, super is strictly limited to calling from inside the subclass to the superclass.不,没有办法像那样颠覆继承的概念。
No, there is no way to subvert the concept of inheritance like that.
很难想象当你需要这样的东西时的情况。
您可以禁止方法重写。
您也可以考虑模板方法模式技术。
It is hard to imagine situation when you need thing like this.
You can forbid method overriding.
Also you can consider Template Method pattern technique.
简单的答案是:你不能
让 blah 成为
或走原始的 Blah 方式,或者完全解耦 blah 实现以便能够调用你需要的任何实现,但仅此而已。
Simple answer is : you can't
you could have blah be
or go the originalBlah way, or decouple the blah implementation altogether to be able to call whichever implementation you need but that's about it.