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开发者_StackOverflow中文版 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)?
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.
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.
精彩评论