示例1
public static void main(String[] args) {
Object obj1 = "好好学习,天天向上";
//传统代码
if (obj1 instanceof String) {
String str = (String) obj1;
System.out.println(str);
} else {
System.out.println("不是字符串类型");
}
//使用新特性
//如果是String类型,直接将其值赋给变量str,该str的作用域仅限于if语句
if (obj1 instanceof String str) {
System.out.println(str);
} else {
System.out.println("不是字符串类型");
}
}
示例2
public class Point {
private double x;
private double y;
@Override
public boolean equals(Object obj) {
return obj instanceof Point other && this.x == other.x && this.y == other.y;
}
}