题目:
Employee员工类中有姓名和月工资的属性(private),还有计算年工资的getAnnual方法;
普通员工类中有work方法,继承Employee类;
经理类有bouns奖金属性和manage管理方法,也继承Employee类;
普通员工类和经理类都重写父类的getAnnual方法;
测试类中添加一个方法show(Employee e),实现获取员工对象年工资,并在main方法中调用该方法;
在测试类中创建一个testwork方法,如果是普通员工调用work,如果是经理,调用manage方法;
解答:
父类
package polyarr;
public class Employee {
private String name;
private double salary;
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getAnnual(){
return getSalary()*12;
}
}
子类
public class NormalEmployee extends Employee {
public NormalEmployee(String name, double salary) {
super(name, salary);
}
public void work() {
System.out.println( "普通员工" + getName() + "在工作");
}
@Override
public double getAnnual() {
return super.getAnnual();
}
}
子类
public class Manager extends Employee {
private double bonus;
public Manager(String name, double salary, double bonus) {
super(name, salary);
this.bonus = bonus;
}
public void manage() {
System.out.println( "经理" + getName() + "在演讲");
}
public double getBonus() {
return bonus;
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
@Override
public double getAnnual() {
return super.getAnnual()+bonus;
}
}
调用类
public class TestEM {
public static void main(String[] args) {
NormalEmployee normal = new NormalEmployee("", 1000);
Manager manager = new Manager("lisi", 100, 30000);
TestEM t = new TestEM();
t.show(normal);
t.show(manager);
t.testwork(normal);
t.testwork(manager);
}
public void show(Employee e) {
System.out.println(e.getAnnual());
}
public void testwork(Employee e) {
if (e instanceof NormalEmployee) {
NormalEmployee n = (NormalEmployee) e;
n.work();
} else if (e instanceof Manager) {
Manager m = (Manager) e;
m.manage();
} else {
System.out.println("111");
}
}
}
输出结果:
12000.0
31200.0
普通员工在工作
经理lisi在演讲