instanceof和类型之间的转换

public class Application {
   public static void main(String[] args) {
       //Object >String
       //Object >Person>Student
       //Object >Person>Teacher
       //System.out.println(X instanceof y);能不能编译通过
//       Object obj = new Student();
//       System.out.println(obj instanceof Student);
//       System.out.println(obj instanceof Teacher);
//       Person person = new Student();
//       System.out.println(person instanceof Student);
//       System.out.println(person instanceof Teacher);
//       System.out.println(person instanceof Object);
       //类型之间的转换 :父   子
       //高                 低
       Person obj = new Student();
       //obj将这个对象转换为Student类型,就可以使用Student类型的方法
      ((Student)obj).go();

       /*
       * 1.父类引用指向子类的对象
       *2.把子类转换为父类,向上转型
       * 3.把父类转换为子类,向下转型:强制转换
       * 4.方便方法的调用,减少重复的代码
       * */

  }
}
=======================================================
   public class Student extends Person{
   public void go(){
       System.out.println("go");
  }

}
=======================================================
   public class Person {
   public void run(){
       System.out.println("run");
  }

}
========================================================
   public class Teacher extends Person{
}
 
posted @ 2024-01-18 17:48  fightownself  阅读(2)  评论(0编辑  收藏  举报