instanceof

  • instanceof (类型转换)引用类型,判断一个对象是什么类型

`

    //Object>Person>Student
    //Object>Person>Teacher
    //Object>String

    //System.out.println(X instanceof Y);存在父子关系编译通过
    Object object = new Student();

    System.out.println(object instanceof Student);//true
    System.out.println(object instanceof Person);//true
    System.out.println(object instanceof Object);//true
    System.out.println(object instanceof Teacher);//false
    System.out.println(object instanceof String);//false
    System.out.println("===============================");

    Person Person = new Student();
    System.out.println(Person instanceof Student);//true
    System.out.println(Person instanceof Person);//true
    System.out.println(Person instanceof Object);//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 Student);//true
    System.out.println(student instanceof Person);//true
    System.out.println(student instanceof Object);//true
    //System.out.println(student instanceof Teacher);//编译报错
    //System.out.println(student instanceof String);//编译报错

`

`

//父类
public class Person {
public void run(){
    System.out.println("sjy");
}
}
============================
//子类
public class Student extends Person{
public void go(){
    System.out.println("go");
}
}
============================
public class Application {
public static void main(String[] args) {
    //类型之间转换  父    子
    Person obj = new Student();
    //student将这个对象转换为Student类型 ,就可以调用student类型的方法了
    ((Student)obj).go();//强转

    //子类型转换为父类有可能丢失一些方法
    Student student = new Student();
    student.go();
    Person person=student;

}
}

/*
  1.父类引用指向子类对象
  2.把子类转换为父类,向上转型
  3.把父类转化为子类,向下转型 需要强制转换  有可能丢失方法
  4.方便方法调用,减少重复代码

  抽象:封装 继承 多态
 * */

`
instanceof

上一篇:c语言求最大公约数和最小公倍数


下一篇:mybatis学习(五)----实现关联表查询