Java Inheritance Programming - Employee class with methods called work, getSalary
Java Inheritance: Exercise-4 with Solution
Write a Java program to create a class called Employee with methods called work() and getSalary(). Create a subclass called HRManager that overrides the work() method and adds a new method called addEmployee().
Sample Solution:
Java Code:
// Employee.java
// Parent class Employee
public class Employee {
private int salary;
public Employee(int salary) {
this.salary = salary;
}
public void work() {
System.out.println("working as an employee!");
}
public int getSalary() {
return salary;
}
}
// HRManager.java
// Child class HRManager
public class HRManager extends Employee {
public HRManager(int salary) {
super(salary);
}
public void work() {
System.out.println("\nManaging employees");
}
public void addEmployee() {
System.out.println("\nAdding new employee!");
}
}
// Main.java
// Main class
public class Main {
public static void main(String[] args) {
Employee emp = new Employee(40000);
HRManager mgr = new HRManager(70000);
emp.work();
System.out.println("Employee salary: " + emp.getSalary());
mgr.work();
System.out.println("Manager salary: " + mgr.getSalary());
mgr.addEmployee();
}
}
Sample Output:
working as an employee! Employee salary: 40000 Managing employees Manager salary: 70000 Adding new employee!
Explanation:
In the above exercise, the Employee class has a work() method that prints a message and a getSalary() method that returns the employee's salary. The HRManager subclass extends the Employee class and overrides the work() method to display a different message. It adds a method addEmployee() that prints a message indicating that a new employee is being added. The Main class creates an instance of Employee and HRManager, calls the work() and getSalary() methods, and also calls the addEmployee() method on the HRManager object.
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Create a class called Shape with a method called getArea and a subclass called Rectangle.
Next: BankAccount class with methods called deposit() and withdraw().
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics