JAVA - instanceof 模式匹配

发布时间 2023-10-01 21:57:31作者: chuangzhou

父类:

package com.demo;

import java.time.LocalDate;

public class Employee {

    private String name;
    private double salary;
    private LocalDate hireDay;


    public Employee(String name, double salary, int year,int month, int day){
        this.name = name;
        this.salary = salary;
        this.hireDay = LocalDate.of(year, month,day);
    }

    public String getName() {
        return name;
    }

    public double getSalary() {
        return salary;
    }

    public LocalDate getHireDay() {
        return hireDay;
    }


    public void raiseSalary(double byPercent){
        double raise = salary * byPercent / 100;
        salary += raise;
    }
}

子类:

package com.demo;

public class Manager extends  Employee{

    private double bouns;

    public Manager(String name, double salary, int year, int month, int day) {
        super(name, salary, year, month, day);
        bouns = 0;
    }

    public double getSalary(){
        double salary = super.getSalary();
        return salary + bouns;
    }

    public void setBouns(double b){
        bouns = b;
    }
}

测试类:

package com.demo;

public class ManagerTest {

    public static void main(String[] args) {

        var boss = new Manager("Carl Craker", 80000,1987,12,15);
        boss.setBouns(5000);

        var staff  = new Employee[3]; // java 10 新特性:如果可以从变量的初始值推到出它们的类型,
                                      // 那么可以使用car关键字声明变量类,无须指定类型

        staff[0] = boss;
        staff[1] = new Employee("Harry Hacker", 50000,1989,10,1);
        staff[2] = new Employee("Tommy Tester", 40000,1990,3,15);


        if (staff[0] instanceof Manager){
            Manager boss2 = (Manager) staff[0];
            System.out.println(boss2.getSalary());
        }
    }
}

对于以下类型写法有些冗余,Manager 被提及了三次

if (staff[0] instanceof Manager){
    Manager boss2 = (Manager) staff[0];
    System.out.println(boss2.getSalary());
}

在Java16中,还有一种更简便的写法。可以直接在instanceof 测试中声明子类变量:

if (staff[0] instanceof Manager boss2){
    System.out.println(boss2.getSalary());
}


//还可以有其他类似的用法
if (staff[0] instanceof Manager m && m.getSalary() >10000){
    System.out.println(m.getSalary());
}

//比如 三元运算符的用法
double bouns =  staff[0] instanceof Manager m ? m.getSalary() : 0;