Java 16新特性 record类 和 instanceof模式匹配,多行代码块
- 记录类型本质上也是一个普通的类,不过是final类型且继承自java.lang.Record抽象类的,它会在编译时,会自动编译出 public get hashcode 、equals、toString 等方法
record 类
//Java 16 新特性record
record Account(String username, String password) { //直接把字段写在括号中
}
record 类的使用
public static void main(String[] args) {
var a = new Account("karl", "123456");
var a1 = new Account("karl", "123456");
System.out.println(a.username());//karl
System.out.println(a.password());//123456
System.out.println(a.toString());//Account[username=karl, password=123456]
System.out.println(a.equals(a1));//true
}
instanceof 模式匹配
- 之前我们一直都是采用这种先判断类型,然后类型转换,最后才能使用的方式
- 新版本我们可以直接将student替换为模式变量:
@Test
public void test1() {
Peo p = new Stu();
// 新版本的写法
if (p instanceof Stu stu2) {
stu2.study();
}
// 老版本的写法
if (p instanceof Stu) {
Stu stu = (Stu) p;
stu.study();
}
}
class Peo { }//父类
class Stu extends Peo {
public void study() {
System.out.println("学生学习");
}
}
多行代码块
新版本直接用"““多行字符串””" 不用转义字符
@Test
public void test2() {
// """多行字符串""" 不用转义字符
// 新版本
var st = """
select * from emp
where id = 1
""";
// 老版本
var st1 ="select * from emp\n where id = 1";
System.out.println(st);
System.out.println(st1);
}