instanceof

instanceof

public class Person {
  public void run(){
      System.out.println("run");
  }
}
public class Stendyent extends Person{
  public void go(){
      System.out.println("go");
  }
}
public class Teacher extends Person{
}
public class AppLication {
  public static void main(String[] args) {
      //类型之间的转换:父(高) 子(低)
      Person s = new Stendyent();
      //将s对象强制转换为Stendyent类型就可以使用go方法,强制转换可能会丢失一些自己本来的方法
      ((Stendyent) s).go();

      /*Object object = new Stendyent();
      //System.out.println(x instanceof y);能不能编译通过主要看两者之间有没有父子关系

      //Object > Person > Stuendy
      System.out.println(object instanceof Stendyent);//true
      System.out.println(object instanceof Person);//true
      System.out.println(object instanceof Object);//true
      //Object > Person > Teacher
      System.out.println(object instanceof Teacher);//false
      //Object > String
      System.out.println(object instanceof String);//false

      System.out.println("==================");

      Person person = new Stendyent();

      System.out.println(person instanceof Stendyent);//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("==================");

      Stendyent stendyent = new Stendyent();

      System.out.println(stendyent instanceof Stendyent);//true
      System.out.println(stendyent instanceof Person);//true
      System.out.println(stendyent instanceof Object);//true
      //System.out.println(stendyent instanceof Teacher);//编译器报错
      //System.out.println(stendyent instanceof String);//编译器报错
        */
  }
}
上一篇:Java面向对象之instanceof和类型转换


下一篇:面向对象05多态