- /*
- * instanceof用于判断对象是否属于该类,返回boolean类型(true/false)
- * 定义一个父类Person,2个子类Student、Teacher
- */
- class Person{}
- class Student extends Person{}
- class Teacher extends Person{}
- public class Test_01 {
- public static void main(String[] args) {
- //字符串本身就是对象属于String,所以true
- System.out.println("hello" instanceof String);
-
- //ss是学生的对象,所以true
- Student ss=new Student();
- System.out.println(ss instanceof Student);
-
- //学生和老师都继承了人,这两个的对象也都属于人,所以true
- Teacher tt=new Teacher();
- System.out.println(tt instanceof Person);
-
- //pp是人的对象,但不是子类老师的对象,所以false
- Person pp=new Person();
- System.out.println(pp instanceof Teacher);
-
- // 运行结果:
- // true
- // true
- // true
- // false
- }
- }
复制代码
|