简体   繁体   中英

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

不,没有办法像这样颠覆继承的概念。

As I understand you want to do something like 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM