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 三原色的配色当然是为了记得更牢固了,遗留的问题后面再说