Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you call a base class function in a function overriding?

To access the overridden function of the base class, we use the scope resolution operator :: . We can also access the overridden function by using a pointer of the base class to point to an object of the derived class and then calling the function from that pointer.

How do you access the overridden method of base class from the derived?

6. How to access the overridden method of base class from the derived class? Explanation: Scope resolution operator :: can be used to access the base class method even if overridden. To access those, first base class name should be written followed by the scope resolution operator and then the method name.

How do I call a method defined in a base class from a derived class that overrides it?

An override method is a new implementation of a member that is inherited from a base class. The overridden base method must be virtual, abstract, or override. Here the base class is inherited in the derived class and the method gfg() which has the same signature in both the classes, is overridden.


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
}

Answer is as follows:

super.Mymethod();
super();                // calls base class Superclass constructor.
super(parameter list);          // calls base class parameterized constructor.
super.method();         // calls base class method.

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 */ 
    }
}

call super.myMethod();