instanceof关键字
instanceof (类型转换)引用类型,判断一个对像是什么类型,判断结果为boolean类型
instanceof 是 Java 的一个二元操作符,左边是对象,右边是类,用法类似于 ==,>,< 等操作符。
instanceof 是 Java 的保留关键字。它的作用是测试它左边的对象是否是它右边的类的实例,返回 boolean 的数据类型。
obj instanceof Class
//其中,obj 是一个对象,Class 表示一个类或接口。
//obj 是 class 类(或接口)的实例或者子类实例时,结果 result 返回 true,否则返回 false。
例如:
//父类Person
public class Person {
}
//子类Student
public class Student extends Person {
}
子类Man
public class Man extends Person{
}
//测试类
public class Test {
public static void main(String[] args) {
//Object>String
//Object>Person>Man
//object>person>student
Object o1 = new Student();
System.out.println(o1 instanceof Student);//true
System.out.println(o1 instanceof Person);//true
System.out.println(o1 instanceof Object);//true
System.out.println(o1 instanceof Man);//false
System.out.println(o1 instanceof String);//false
System.out.println("======================================");
Person p1 = new Student();
System.out.println(p1 instanceof Student);//true
System.out.println(p1 instanceof Person);//true
System.out.println(p1 instanceof Object);//true
System.out.println(p1 instanceof Man);//false
//System.out.println(p1 instanceof String);//编译报错!
System.out.println("======================================");
Student s1 = new Student();
System.out.println(s1 instanceof Student);//true
System.out.println(s1 instanceof Person);//true
System.out.println(s1 instanceof Object);//true
//System.out.println(s1 instanceof Man);//编译报错!
//System.out.println(s1 instanceof String);//编译报错!
}
}
公式:
S instanceof Y
能不能编译通过,取决于 X 和 Y 是否存在父子关系,如果存在父子关系,编译通过,如果没有父子关系,编译报错
- 类的实例包含本身的实例,以及所有直接或间接子类的实例
- instanceof左边显式声明的类型与右边操作元必须是同种类或存在继承关系,也就是说需要位于同一个继承树,否则会编译错误(如Person与String、Student与Man)
- null用instanceof跟任何类型比较时都是false
类型转换
子类转换成父类,父类转换成子类(强制类型转换)
//父类
public class Person {
public void run(){//父类中存在一个方法run
System.out.println("run");
}
}
//子类
public class Student extends Person {
public void go(){//go方法是父类中没有的
System.out.println("go");
}
}
//测试类
public class Test {
public static void main(String[] args) {
//类型转换:父-->子
//高 低
Person obj = new Student();
//obj是Person类型的,将这个对象转换成Student类型,我们就能使用Student类型的方法了。
Student student=(Student)obj;
student.go();
//或者
((Student)obj).go();
//子类转换为父类可能会丢失一些方法
Student student1 = new Student();
student1.go();
Person person = student;//子类转换成父类
}
}
多态总结
1、父类引用指向子类的对象。
2、把子类转换成父类,向上转型
3、把父类转换成子类,向下转型,强制转换
3、方便方法的调用,减少重复的代码