The two have a lot in common for their experience working in the same company and employees. For example, salary is paid every month, but the manager will also receive a bonus after completing the target task. At this time, using employee classes to write manager classes will write less code, and using inheritance technology can allow manager classes to use attributes and methods defined in employee classes. Write programs that demonstrate the differences between managers and employees by inheriting.
Idea analysis: typical inheritance problem. The parent class is the employee class, and the subclass is the manager class. The manager class inherits the employee class, so that only additional bonuses are implemented in the manager class, that is, the member variables representing the bonus and the member methods for setting and obtaining bonuses.
The code is as follows:
The code copy is as follows:
import java.util.Date;
public class Employee {
private String name; //The employee's name
private double salary; //Employee's salary
private Date birthday; //Employee's birthday
public String getName() { //Get the employee's name
return name;
}
public void setName(String name) { //Set the employee's name
this.name = name;
}
public double getSalary() { //Get employee salary
return salary;
}
public void setSalary(double salary) { //Set the salary of employees
this.salary = salary;
}
public Date getBirthday() { //Get the employee's birthday
return birthday;
}
public void setBirthday(Date birthday) { //Set the employee's birthday
this.birthday = birthday;
}
}
public class Manager extends Employee {
private double bonus;// Manager's bonus
public double getBonus() {// Get the manager's bonus
return bonus;
}
public void setBonus(double bonus) {// Set the manager's bonus
this.bonus = bonus;
}
}
import java.util.Date;
public class Test {
public static void main(String[] args) {
Employee employee = new Employee();//Create an Employee object and assign a value to it
employee.setName("Java");
employee.setSalary(100);
employee.setBirthday(new Date());
Manager manager = new Manager();//Create Manager object and assign it a value
manager.setName("Tomorrow Technology");
manager.setSalary(3000);
manager.setBirthday(new Date());
manager.setBonus(2000);
//Output manager and employee attribute values
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 shown in the figure: