Java关键字:instanceof

Java关键字:instanceof

java 中的instanceof 运算符是用来在运行时指出对象是否是特定类的一个实例。

它会返回一个布尔值,如果前面的对象是后面类的实例,则返回true,否则返回false

重点:

  1. instanceof后面如果是实现的接口也返回true
  2. instanceof后面如果是实例的父类也返回true

示例:

class Person{
	public String name;
  	public boolean gender;
  	public int age;
  	public Person(){};
}

interface Worker{//职员接口
	public void work();
	public void rest();
}

class Teacher extends Person implements Worker{//教师继承Person实现Worker
	public Teacher() {super();}
	public void work() {}
	public void rest() {};
}

class Untitled {
	public static void main(String[] args) {
		Person one = new Person();
		Teacher two = new Teacher();
      	System.out.println(one instanceof Person);//输出True
      	System.out.println(two instanceof Person);//输出True
      	System.out.println(one instanceof Teacher);//输出False
      	System.out.println(two instanceof Worker);//输出True
	}
}
3+
Rhett Peng

软件工程大三在读学生,用个人网站记录学习动态

说点什么

avatar