简体   繁体   中英

Calling parent method using child class object in Java

Is there a way to call the parent class methods which are overridden by the child class using a child class object? I know that you can use super.foo() inside the overridden method to redirect the call to the parent class method but is there a way that doesn't involves going into the child class method first before calling the parent method?

No.

If an object of class Child is called to do x() , then in Java, it's the responsibility of its class ( Child ) to supply the correct implementation. So, the Child class is always in charge, and it's the sole decision of the Child class whether to call its parent class method in the process of serving the x() call.

If you find situations where the child class implementation is not appropriate for servicing the x() call, then that's a bug of this Child.x() method implementation, and you have to fix that implementation to correctly serve the call.

If, for some given call parameters, the child class can't tell how to correctly serve the call, then the design of that method (as a contract between caller and callee) is flawed, and you should clean that up, eg make two different methods from x() .

You don't have to call super.foo() from the child class implementation of foo().

public class Main {

    static class A {
        void foo() {
            System.out.println("A.foo()");
        }
    }

    static class B extends A {
        void foo() {
            System.out.println("B.foo()");
        }
        void bar() {
            super.foo();
        }
    }

    public static void main(String[] args) {
        B b = new B();
        b.bar();
    }
}

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