views:

85

answers:

4

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)?

+2  A: 

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.

Mykola Golubyev
Isn't the `template method` just polymorphism by a different name?
Yar
@yar: Yes and no, `template method` is the name of the pattern where each implementation differ only by some really minute detail and thus don't really need that much extra/override code to do their job. As always, Wikipedia's example is a bit confusing, check these two links for more info: http://c2.com/cgi/wiki?TemplateMethod http://www.javapractices.com/topic/TopicAction.do?Id=164
Esko
Excellent, thanks Mykola and @Esko
Yar
@Esko, thanks again for that. I see now that the hook method -- template method -- is what I use all the time to give API clients a concrete implementation. Now I know what it's called.
Yar
+3  A: 

No, there is no way to subvert the concept of inheritance like that.

Michael Borgwardt
Thanks, that's what I saw empirically, too...
Yar
+1. If you find that you want to do things like that, then maybe you should look at object composition instead of subclassing, which offers more flexibility to the client code.
Thilo
Thanks @Thilo. I generally avoid subclassing altogether and prefer 'has a' to 'is a' relationships. But this case came up, just wanted to know if Java provides for that.
Yar
+2  A: 

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.

Adrian
Thanks, I was hoping that wasn't true...
Yar
+1  A: 

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.

Jean
Thanks for that.
Yar