[英]Java Hiding: Any Way for Client Classes to Call `super`?
Aside from adding a method explicitly on the subclass to call a super
method, is there anyway to "unhide" it temporarily? 除了在子类上显式添加一个方法来调用一个
super
方法之外,还是要暂时“取消隐藏”它吗? I would like to call the super.blah()
method on a Test2
instance. 我想在
Test2
实例上调用super.blah()
方法。 Must I use a method like originalBlah
, or is there another way? 我必须使用像
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");
}
}
Edit: Sorry to add to the question late in the game, but I had a memory flash (I think): in C# is this different? 编辑:很抱歉在游戏后期添加问题,但我有一个内存闪存(我认为):在C#中这是不同的? That it depends on which class you
think
you have (Test1 or Test2)? 这取决于你
think
你拥有哪个班级(Test1或Test2)?
不,没有办法像这样颠覆继承的概念。
As I understand you want to do something like Test1 b = new Test2(); b.super.blah()
据我所知,你想做一些像
Test1 b = new Test2(); b.super.blah()
Test1 b = new Test2(); b.super.blah()
. Test1 b = new Test2(); b.super.blah()
。 This cannot be done, super is strictly limited to calling from inside the subclass to the superclass. 这是不可能的,super严格限于从子类内部调用到超类。
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. 您还可以考虑模板方法模式技术。
Simple answer is : you can't 简单的答案是:你做不到
you could have blah be 你可能会有
class Test2 extends Test1 {
public void blah() {
if("condition"){
super.blah()
}
System.out.println("test2 says blah");
}
}
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. 或者采用原始的方式,或者完全解除blah实现,以便能够调用您需要的任何实现,但这就是它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.