Is it possible to call base class function without modifying both base and derived classes?
class Employee {
    public String getName() {
        return "Employee";
    }
    public int getSalary() {
        return 5000;
    }
}
class Manager extends Employee {
    public int getBonus() {
        return 1000;
    }
    public int getSalary() {
        return 6000;
    }
}
class Test {
    public static void main(String[] args) {
        Employee em = new Manager();
        System.out.println(em.getName());
        // System.out.println(em.getBonus());
        System.out.println(((Manager) em).getBonus());
        System.out.println(em.getSalary());
    }
}
Output: Employee 1000 6000
How shall I call the Employee's getSalary() method on em object?
As with so many techniques in C++, it is largely a matter of syntax. When you want to call a specific base class's version of a virtual function, just qualify it with the name of the class you are after, as I did in Example 8-16: p->Base::foo();
A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function.
A polymorphic method is a method that can take many forms. By that that I mean, the method may at different times invoke different methods. Let's say you got a class Animal and a class Dog extends Animal and a class Cat extends Animal , and they all override the method sleep() Then.. animal.sleep();
A derived Java class can call a constructor in its base class using the super keyword. In fact, a constructor in the derived class must call the super's constructor unless default constructors are in place for both classes.
You can't. You could add a method like this to Manager if you wanted:
public int getEmployeeSalary()
{
    return super.getSalary();
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With