The two have a lot in common with the experience of working in the same company and the staff. For example, a paycheck is paid every month, but the manager gets a bonus when he or she finishes the target task. At this point, using an employee class to write a manager class will write less code, using inheritance technology to let the manager class use the attributes and methods defined in the Employee class. Write programs that demonstrate differences between managers and employees by inheriting.
Thinking Analysis: A typical inheritance problem. The parent class is the employee class, the subclass is the manager class, and the manager class inherits the employee class, so that the manager class only uses an extra bonus, that is, to increase the member variables and settings for the bonus and the member method that gets the bonus.
The code is as follows:
Copy Code code as follows:
Import Java.util.Date;
public class Employee {
private String name; Employee's name
private double salary; Employee's salary
Private Date birthday; Employee's Birthday
Public String GetName () {//Get employee's name
return name;
}
public void SetName (String name) {//Set employee's name
THIS.name = name;
}
Public double getsalary () {//Get employee's wages
return salary;
}
public void Setsalary (double salary) {//Set employee's wages
This.salary = salary;
}
Public Date Getbirthday () {//Get employee's birthday
return birthday;
}
public void Setbirthday (Date birthday) {//Set employee's birthday
This.birthday = Birthday;
}
}
public class Manager extends Employee {
Private double bonus;//manager's bonus
Public double Getbonus () {//Get manager's Bonus
return bonus;
}
public void Setbonus (double bonus) {//Set manager's bonus
This.bonus = bonus;
}
}
Import Java.util.Date;
public class Test {
public static void Main (string[] args) {
Employee Employee = new Employee ();//Create Employee object and assign value to it
Employee.setname ("Java");
Employee.setsalary (100);
Employee.setbirthday (New Date ());
Manager Manager = new manager ();//Create Manager object and assign value to it
Manager.setname ("Tomorrow Technology");
Manager.setsalary (3000);
Manager.setbirthday (New Date ());
Manager.setbonus (2000);
Output property values for managers and employees
SYSTEM.OUT.PRINTLN ("Employee's name:" + employee.getname ());
SYSTEM.OUT.PRINTLN ("Employee's Salary:" + employee.getsalary ());
SYSTEM.OUT.PRINTLN ("Employee's Birthday:" + employee.getbirthday ());
System.out.println ("Manager's name:" + manager.getname ());
System.out.println ("Manager's Salary:" + manager.getsalary ());
System.out.println ("Manager's Birthday:" + manager.getbirthday ());
System.out.println ("Manager's Bonus:" + Manager.getbonus ());
}
}
The effect is as shown in the figure: