John Eipe
John Eipe

Reputation: 11228

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?

Upvotes: 5

Views: 2260

Answers (3)

Mechkov
Mechkov

Reputation: 4324

You can call the superclass's method from within the subclass.

class Manager extends Employee {
    public int getBonus() {
    return 1000;
    }

    public int getSalary() {
    return super.getSalary();
    }
}

Upvotes: 0

Puce
Puce

Reputation: 38132

Use an Employee object instead:

Employee em = new Employee();

Upvotes: 0

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

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

public int getEmployeeSalary()
{
    return super.getSalary();
}

Upvotes: 6

Related Questions