instanceOf用法

首先,先了解向上转型和向下转型:

 

 

public class Person {
    private Integer age;
    private String name;
}

  

public class Student extends Person {
    private String student_no;
}

 其中Student类继承了Person类。

Person p = new Student();   这个属于向上转型,person类本来没有student_no属性,然后现在指向了student类,变多出了相关的属性。

Student s =(Student)p; 这个属于向下转型,Student类指向了person类,那么原来的student_no属性就会存在丢失的情况。

  因此在向下转型的时候,我们需要用instanceof来判断Person是不是student的实例

 

https://www.cnblogs.com/ysocean/p/8486500.html  

Java关键字(一)——instanceof

posted @ 2020-03-13 11:03  曾饺  阅读(354)  评论(0)    收藏  举报