Create a class Employee which has two data memeber name and id and a funtion to take input. Derive two classes "Regular" and "Part_Time". In Regular class, calculate the gross salary using Formula, Gross salary = Basic Salary+HA+DRA,where HA and DRA should be stored as static data member of class. In Part_Time class, Calculate the salary of Part_Time Employee using Formula Gross salary = Pay per hrs * no. of hrs. where pay per hrs is should be stored as static const.
Objective
Write a Java program to implement an Employee payroll system using inheritance and static constants.
Algorithm / Approach
- Create a base class
Employeewith standard fields (name, id) and static constants for allowances and pay rates. - Create a derived class
Regularthat adds a basic salary field and calculates gross salary including allowances. - Create another derived class
Part_Timethat calculates salary based on hours worked multiplied by the pay rate. - Use the
super.input()mechanism to avoid rewriting the name/id prompt logic.
Employee.java
import java.util.*;
class Employee{
String name;
int id;
static final int HA = 3000;
static final int DRA = 5000;
static final int pay = 1000;
Scanner s=new Scanner(System.in);
void input() {
System.out.print("Enter Name: ");
name = s.nextLine();
System.out.print("Enter Id: ");
id = s.nextInt();
}
}
class Regular extends Employee {
int bsal,gsal;
void input() {
System.out.println("Regular Emp");
super.input();
System.out.print("Enter Salary: ");
bsal = s.nextInt();
}
void display() {
gsal = bsal+HA+DRA;
System.out.println("Salary- "+gsal);
}
}
class Part_Time extends Employee {
int hr,gsal;
void input() {
System.out.println("Part_Time EMP");
super.input();
System.out.print("Enter No. of Hrs: ");
hr = s.nextInt();
}
void display() {
gsal = hr*pay;
System.out.println("Income- "+gsal);
}
}
class Salary {
public static void main(String[] a)
{
Regular r= new Regular();
r.input();
r.display();
Part_Time p = new Part_Time();
p.input();
p.display();
}
}
Expected Output
Regular Emp Enter Name: Alok Enter Id: 13 Enter Salary: 25000 Salary- 33000 Part_Time EMP Enter Name: Deepak Enter Id: 30 Enter No. of Hrs: 30 Income- 30000
Explanation of the Program
- This program combines Hierarchical Inheritance with the
superkeyword andstatic finalconstants. - Constants like HA (House Allowance) and DRA are shared across all employees, making them perfect candidates for the
static finalmodifier. - The
RegularandPart_Timeclasses share the core employee identity data but implement entirely different payroll calculation logic.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)