0

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?

1
  • 1
    If this is the situation which you need to face then the design of the program is poor and you must consider redesigning. The more you apply patches to break the OOPS pinrinciples the more dirty and unmanageable code will become. Commented Nov 5, 2020 at 16:51

2 Answers 2

1

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, e.g. make two different methods from x().

Sign up to request clarification or add additional context in comments.

Comments

1

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();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.