面向对象编程4

补充 instanceof

instanceof 类型转换 引用类型 用于判断一个对象是什么类型

package javaSE.oop.Demo06;

public class Person {
   public void run(){
       System.out.println("run");
  }
}
package javaSE.oop.Demo06;

public class Students extends Person{

}
package javaSE.oop.Demo06;

public class Teacher extends Person{
}
package javaSE.oop;

import javaSE.oop.Demo06.Person;
import javaSE.oop.Demo06.Students;
import javaSE.oop.Demo06.Teacher;

public class Application {

   /*
   Object>String
   Object>Person>Teacher
   Object>Person>Students
    */
   public static void main(String[] args) {
       Object object = new Students();
       //instanceof :用于判断一个对象是什么类型
       System.out.println(object instanceof Students);//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

       Person person = new Students();
       System.out.println("==================");
       System.out.println(person instanceof Students);//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);//编译报错,Person与String同级

       Students students = new Students();
       System.out.println("==================");
       System.out.println(students instanceof Students);//true
       System.out.println(students instanceof Person);//true
       System.out.println(students instanceof Object);//true
       //System.out.println(students instanceof Teacher);//编译报错
       //System.out.println(students instanceof String);//编译报错
  }

}

 

类型转换

把子类转换为父类,向上转型 自动转换

把父类转换为子类,向下转型 强制转换

子类转换为父类可能丢失自己本来的一些方法

package javaSE.oop.Demo06;

public class Students extends Person{

   public void go(){
       System.out.println("go");
  }
}
package javaSE.oop;

import javaSE.oop.Demo06.Person;
import javaSE.oop.Demo06.Students;

public class Application {

   public static void main(String[] args) {
       //类型之间的转换   父类 子类

       //高                     低
       Person obj = new Students();

       //students将这个对象转换为Students类型,我们就可以使用Students类型的方法了
       //Students.go(); //无法调用go
       Students students = (Students) obj;
       students.go();
       //or
      ((Students)obj).run();

       //子类转换为父类可能丢失自己本来的一些方法
  }

}
 
posted @ 2022-05-12 21:01  唐靈影  阅读(86)  评论(0)    收藏  举报