韩顺平第八章多态的题②
package polyparemeter;
public class Employ {
private String name;
private double salary;
public Employ(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 12*salary;
}
}
父类
package polyparemeter;
public class Manager extends Employ{
private double bonus;
public Manager(String name, double salary, double bonus) {
super(name, salary);
this.bonus = bonus;
}
public double getBonus() {
return bonus;
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
public String manage(){
return "经理" + getName() + "薪资" + getSalary() + "正在管理";
}
public double getAnnual(){
return 12*(super.getSalary() + bonus);
}
}
子类
package polyparemeter;
public class Worker extends Employ{
public Worker(String name, double salary) {
super(name, salary);
}
public String work(){
return "员工" + getName() + "薪资" + getSalary() + "正在工作";
}
public double getAnnual(){
return 12*(super.getSalary());
}
}
子类
package polyparemeter;
class Test {
public void testWork(Employ e) {
if (e instanceof Worker){
System.out.println(((Worker)e).work());
}else if(e instanceof Manager){
System.out.println(((Manager) e).manage());
}else{
System.out.println("输入错误");
}
}
public void showEmpAnnual(Employ e){
System.out.println( e.getAnnual());
}
public static void main(String[] args) {
// 第二种方法,多态参数
Manager manager = new Manager("ZJH",2,8);
Worker worker = new Worker("LGD",1);
Test test = new Test();
test.showEmpAnnual(manager);
test.showEmpAnnual(worker);
test.testWork(manager);
test.testWork(worker);
}
}
主方法,第一种
package polyparemeter;
public class Test2 {
public void testWork(Employ e) {
if (e instanceof Worker){
System.out.println(((Worker)e).work());
}else if(e instanceof Manager){
System.out.println(((Manager)e).manage());
}else{
System.out.println("输入错误");
}
}
public void showEmpAnnual(Employ e) {
System.out.println(e.getAnnual());
}
public static void main(String[] args) {
// 第一种方法,向上转型
Employ employ = new Manager("ZJH", 2, 8);
Employ employ1 = new Worker("LG", 1);
Test2 test = new Test2();
test.showEmpAnnual(employ);
test.showEmpAnnual(employ1);
test.testWork(employ);
test.testWork(employ1);
}
}
子方法第二种



