简体   繁体   中英

Does the return keyword in a superclass method return to the subclass that called the superclass method?

As stated in the title, pertaining specifically to Java. In pseudocode an example of this might be:

class SubClass extends SuperClass {
    protected void update() {
        super.update()
        // do other functionality
    }
}

class SuperClass {
    protected void update() {
        if (something) return;
    }
}

If the update method is called and the superclass then returns, does the other functionality in the subclass then execute or does it return fully to where the original subclass method is called?

As a follow up question, if this is not the case, is there a way to effectively prevent any further code from running in the superclass or subclass methods?

There's nothing special about the method call from the subclass to the superclass (other than which method gets called, which the super keyword influences, obviously). The answers to your questions flow from that fact:

Does the return keyword in a superclass method return to the subclass that called the superclass method?

Yes, just like any other method call. Sometimes, the subclass needs to do work after the superclass work is done, and/or with the return value from the superclass before returning to the caller.

...is there a way to effectively prevent any further code from running in the superclass or subclass methods?

Not from the superclass method, no. You can throw an exception, but (of course) the subclass method could catch it. Which is, again, just like any other method call.

Because the type of the method is protected, access from subclasses is possible. Also void methods do not return.

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