【instanceof 关键字的用法】

本文详细介绍了Java中的instanceof关键字,包括其使用格式、判断对象类型、在多态和转型中的应用,以及在编译问题和三目运算符中的注意事项。通过示例代码展示了如何判断对象是否为类或接口的实例,以及在继承层次中的行为。同时,文章指出了使用instanceof时的限制和潜在的编译问题。
摘要由CSDN通过智能技术生成

1:使用格式与说明

Java 中可以使用 instanceof 关键字判断一个对象是否为一个类(或接口、抽象类、父类)的实例

代码格式——boolean result = obj instanceof Class

返回一个boolean类型的数值

2:具体用法

2.1 判断是否为class 类的实例对象
//这个表述方式在jdk1.9之后被逐渐废弃
//现在使用最多的是
//Integer i=Integer.valueof(1)
Integer integer = new Integer(1);  

System.out.println(integer instanceof  Integer);   
// true

2.2在实现类的使用

添加一个代码段

** instanceof 运算符判断 ArrayList 类的对象是否属于 List 接口的实例**

ArrayList arrayList = new ArrayList(); 

System.out.println(arrayList instanceof List);    
// true

返过来也是可以的


List list = new ArrayList();  

System.out.println(list instanceof ArrayList);  
// true

2.3直接子类或者间接子类

下面这个代码第二条输出语句需要完善

//测试instanceof关键字  
public class cast {  
    public static void main(String[] args) {  
     cast c =new cast01();  
        System.out.println(c instanceof cast);  
        System.out.println(c instanceof cast01);  
    }  
}  
class cast01 extends cast{  
}
//打印结果
//true
//true
2.4编译问题
1.  Person p1 = new Person();
2.  System.out.println(p1 instanceof String); // 编译报错
3.  System.out.println(p1 instanceof List); // false
4.  System.out.println(p1 instanceof List<?>); // false
5.  System.out.println(p1 instanceof List<Person>); // 编译报错

**erson 的对象 p1 很明显不能转换为 String 对象,那么
p1 instanceof String
不能通过编译,
p1 instanceof List
却能通过编译,
instanceof List<Person>
又不能通过编译了
**javaSE1.8给出了解释
大致可以理解为以下代码

1.  boolean result;   //假设的方法
2. 
3.  if (obj == null) {
4.  result = false; // 当obj为null时,直接返回false
5.  } else {
6.  try {
7.  // 判断obj是否可以强制转换为T
8.  T temp = (T) obj;
9.  result = true;
10.  } catch (ClassCastException e) {
11.  result = false;
12.  }
13.  }

2.5在三目运算符的使用
//测试instance的三目运算  
public class in_f {   
      public Object animalCall(Animal a) {  
        String tip = "这是一个猪";  
        // 判断参数a是不是Cow的对象  
      return a instanceof Cow ? (Cow) a : tip;  
    }  
     public static void main(String[] args) {  
        Sheep sh = new Sheep();  
        in_f test = new in_f();  
        System.out.println(test.animalCall(sh));  
    } 
}  
class Animal {}  
  
class Cow extends Animal {}  
  
class Sheep extends Animal {}

[[A-多态和转型]]
这是obsidian笔记软件自动跳转链接。

注意

1: obj 的类型必须是引用类型或空类型,否则会编译错误。

2:instanceof 运算符只能用作对象的判断。

3: class 为 null 时,会生生编译错误,所以 class 只能是类或者接口。

RGB 三原色的配色当然是为了记得更牢固了,遗留的问题后面再说

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值