instanceof关键字实例与多态
实例代码如下:
Application类
package com.han.duotai;
/**
* instanceof关键字实例,判断引用类型是否属于一个类型
*
* 关于多态
* 1.父类的引用指向子类的对象
* 2.把子类转换为父类,向上转型
* 3.把父类转换为子类,向下转型,需要进行强制类型转换
* 4.方便方法的调用,减少重复的代码
*/
public class Application {
public static void main(String[] args) {
Object obj = new Student();
System.out.println(obj instanceof Person);//true
System.out.println(obj instanceof Object);//true
System.out.println(obj instanceof Student);//true
System.out.println(obj instanceof Teacher);//false
System.out.println(obj instanceof String);//false
System.out.println("=======================================");
Person person = new Student();
System.out.println(person instanceof Person);//true
System.out.println(person instanceof Object);//true
System.out.println(person instanceof Student);//true
System.out.println(person instanceof Teacher);//false
//System.out.println(person instanceof String);//编译报错
System.out.println("=======================================");
Student student = new Student();
System.out.println(student instanceof Person);//true
System.out.println(student instanceof Object);//true
System.out.println(student instanceof Student);//true
//System.out.println(student instanceof Teacher);//编译报错
//System.out.println(student instanceof String);//编译报错
System.out.println("=======================================");
Person person1 = new Student();
((Student) person1).go();//高转低-->强制类型转换
}
}
Person类
package com.han.duotai;
public class Person {
}
Student类
package com.han.duotai;
public class Student extends Person{
public void go(){
}
}
Teacher类
package com.han.duotai;
public class Teacher extends Person{
}