In Java, how do I call a base class's method from the overriding method in a derived class?

Viewed 278608

I have two Java classes: B, which extends another class A, as follows :

class A {
    public void myMethod() { /* ... */ }
}

class B extends A {
    public void myMethod() { /* Another code */ }
}

I would like to call the A.myMethod() from B.myMethod(). I am coming from the C++ world, and I don't know how to do this basic thing in Java.

12 Answers

The keyword you're looking for is super. See this guide, for instance.

Just call it using super.

public void myMethod()
{
    // B stuff
    super.myMethod();
    // B stuff
}

super.MyMethod() should be called inside the MyMethod() of the class B. So it should be as follows

class A {
    public void myMethod() { /* ... */ }
}

class B extends A {
    public void myMethod() { 
        super.MyMethod();
        /* Another code */ 
    }
}
Related