Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism - Call Base class function

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?

like image 514
John Avatar asked Oct 28 '11 16:10

John


People also ask

How do you call a base class function in C++?

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

How do you call a derived function from base class?

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.

What is a polymorphic method call?

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

How do you call a base class method in Java?

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.


1 Answers

You can't. You could add a method like this to Manager if you wanted:

public int getEmployeeSalary()
{
    return super.getSalary();
}
like image 95
Ernest Friedman-Hill Avatar answered Sep 30 '22 12:09

Ernest Friedman-Hill