多态参数
应用:方法定义的形参类型为父类类型,实参允许为子类类型
package polyparemeter;
public class employee {
private String name;
private double salary;
public employee(){
}
public employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public double getannual(){
return 12 * salary;
}
public String getName() {
return name;
}
public void showannual(employee e){
System.out.println(e);
System.out.println(e.getannual());
System.out.println("\n接着使用instanceof操作符判断,调用独有的方法");
if(e instanceof manager){
manager mag = (manager) e;
mag.manage();
}else if(e instanceof worker){
worker wok = (worker) e;
wok.work();
}
}
}
package polyparemeter;
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() + " is managing");
}
public double getannual(){
return super.getannual() + bonus;
}
}
package polyparemeter;
public class worker extends employee {
public worker(String name, double salary) {
super(name, salary);
}
public void work(){
System.out.println("普通员工 " + getName() + " is working");
}
}
package polyparemeter;
public class main {
public static void main(String[] args) {
worker tom = new worker("tom",2500);
manager smith = new manager("smith",2500,5000);
employee e = new employee();
e.showannual(tom);
System.out.println("==============================");
e.showannual(smith);
}
}
polyparemeter.worker@4554617c
30000.0
接着使用instanceof操作符判断,调用独有的方法
普通员工 tom is working
==============================
polyparemeter.manager@74a14482
35000.0
接着使用instanceof操作符判断,调用独有的方法
经理 smith is managin
代码解释
-
(1)创建了父类employee,两个子类manager和worker继承父类
-
(2)重写getannual()方法,目的是获取每个员工的薪资,在employee类中创建showannual()方法,通过父类的形参接受子类的实参,体现多态参数的应用
-
(3)最后使用instanceof操作符,实现调用两个子类中特有的方法