Bài tập kế thừa trong Java: tạo lớp Employee và Manager theo yêu cầu | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points

Task

Create Employee class and Manager class with the following information:

Explanation:

Employee class

  • name and salary attributes describe the name and salary of an employee.
  • Employee(name: String, salary: int) is the parameter constructor which is used for initializing values to attributes
  • display() method displays the object information on the screen. For example, if name = "Khanh", salary = 1500, when we call display() method, the screen will display as below:
  • Name: Khanh
    Salary: 1500​
  • Other methods are setter and getter.

Manager class

  • This class inherit from Employee class.
  • bonus attribute describes the bonus salary.
  • Manager(name: String, salary: int, bonus: int) is a parameter constructor which is used for initializing values to attributes.
  • setBonus() and getBouns() are setter and getter.
  • getSalary() method overrides Person class, this method returns salary + bonus.
  • display() method overrides Employee. For example, if name = "Binh", salary = 2500, bonus = 1600, when we call display() method, the screen will display as below:
    Name: Binh
    Salary: 4100​

    Explanation: the screen display "Salary = 4100" because salary + bonus = 4100 (the manager has bonus)

Instruction

File Employee.java

public class Employee {
	private String name;
	private int salary;

	public Employee(String name, int salary) {
		super();
		this.name = name;
		this.salary = salary;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getSalary() {
		return salary;
	}

	public void setSalary(int salary) {
		this.salary = salary;
	}

	public void display() {
		System.out.println("Name: " + name);
		System.out.println("Salary: " + salary);
	}
}

File Manager.java

public class Manager extends Employee {
	private int bonus;

	public Manager(String name, int salary, int bonus) {
		super(name, salary);
		this.bonus = bonus;
	}

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

	public int getBonus() {
		return bonus;
	}

	public void setBonus(int bonus) {
		this.bonus = bonus;
	}

	public void display() {
		System.out.println("Name: " + getName());
		System.out.println("Salary: " + getSalary());
	}
}