多态

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

public class Application {

    public static void main(String[] args) {

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

        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);  //编译报错
        
        
    //类型之间的转化    父    子
        //高          低
        Person obj = new Student();
        Student student = (Student) obj;
        student.go();
      ((Student) obj).go();

        Student s1 = new Student();
        ((Person)s1).run();
        //student 将这个对象转换为Student类,我们就可以使用Student类型的方法了


    }

}

//父类:
public class Person {
    public  void run(){
        System.out.println("run");
    }
}
//子类1
public class Student extends Person{
    public void go(){
        System.out.println("go");
    }

}
//子类2

public class Teacher extends Person{
}

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

抽象: 封装、继承、多态

 */
posted @ 2022-04-04 17:22  时装男人  阅读(26)  评论(0)    收藏  举报