您当前的位置: 首页 >  Java

梁云亮

暂无认证

  • 2浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Java14:模式匹配:instanceof

梁云亮 发布时间:2021-10-09 17:30:13 ,浏览量:2

示例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;
    }
}
关注
打赏
1665409997
查看更多评论
立即登录/注册

微信扫码登录

0.0408s