Calculate employee salary by overriding method

Q. Define an Employee class with suitable attributes having getSalary() method, which returns salary withdrawn by a particular employee. Write a class Manager which extends a class Employee, override the getSalary() method, which will return salary of manager by adding traveling _allowance, house rent allowance etc.

Answer:

In this example, we use method overriding to calculate the traveling_allowance, house rent allowance etc. of an employee. Both employee and Manager class have the getSalary() method returning salary withdrawn by a particular employee.

Employee.java

class Employee
{
     String name;
     int salary;
     Employee()
     {
          name = null;
          salary = 0;
     }
     Employee (String name, int salary)
     {
          this.name = name;
          this.salary = salary;
     }
     int getSalary()
     {
          return salary;
     }
}


Manager.java

class Manager extends Employee
{
     int hra, ta;
     Manager()
     {
          super();
          hra = ta = 0;
     }
     Manager(String n, int sal, int h, int t)
     {
          super(n, sal);
          hra = h;
          ta = t;
     }
     int getSalary()
     {
          return (super.getSalary()+hra+ta);
     }
}


Main.java

class Main
{
     public static void main(String[] args)
     {
          Manager m1 = new Manager("Nikhil",20000,500,1500);
          System.out.println("Salary of Manager= "+m1.getSalary());
     }
}


Output:

Salary of Manager= 22000