Reputation: 11228
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
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
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