多态

多态

package com.oop.Demo06;

public class Application {
    public static void main(String[] args) {
        //一个对象的实例类型是确定的
        //但可以指向的引用类型就不确定了:父类的引用指向子类

        //student 能调用的方法都是自己的或者继承父类的
        Student s01 = new Student();
        //Person 父类,可以指向子类,但是不能调用子类独有的方法
        Person s02 = new Student();
        Object s03 = new Student();

        //子类不能指向父类
        //Student s04 = new Person();

        /**
         * 对象能执行哪些方法,主要看对象左边的类型,和右边关系不大
         * 子类重写了父类的方法,执行子类的方法
         *
         * 多态注意事项
         * 1、多态是方法的多态,属性没有多态
         * 2、父类和子类有联系 否则会类型转换异常 eg:String=>Person
         * 3、存在条件:继承关系,方法需要重写,父类引用指向子类对象
         *
         * 不能重写方法的情况:
         * 1、static方法 属于类,不属于实例
         * 2、final修饰 属于常量
         * 3、private修饰的方法,属于私有
         *
         */
        s01.run();
        s01.study();
        s02.run();

        //s02.walk();
    }
}

父类:

package com.oop.Demo06;

public class Person {

    public void run(){
        System.out.println("父类在跑步");
    }
}

子类:

package com.oop.Demo06;

public class Student extends Person{
    @Override
    public void run() {
        System.out.println("子类在跑步");
    }

    public void study(){
        System.out.println("study");
    }
}

instanceof

package com.oop.Demo06;

public class Application {
    public static void main(String[] args) {

        /**
         * x instanceof y//能不能编译通过,看x和y之间是否存在父子关系
         */

        Object obj = new Student();

        System.out.println(obj instanceof Student);//true
        System.out.println(obj instanceof Teacher);//false
        System.out.println(obj instanceof Person);//true
        System.out.println(obj instanceof Object);//true
        System.out.println(obj instanceof String);//false

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

        Person person = new Student();

        System.out.println(person instanceof Student);//true
        System.out.println(person instanceof Teacher);//false
        System.out.println(person instanceof Person);//true
        System.out.println(person instanceof Object);//true
        //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 Teacher);//编译报错
        System.out.println(student instanceof Person);//true
        System.out.println(student instanceof Object);//true
        //System.out.println(student instanceof String);//编译报错

    }
}

父类子类的类型转换

  1. 父类引用指向子类对象

  2. 把子类转换为父类,向上转型

    Student student = new Student();
    student.study();
    Person person = student;
    

    子类转换为父类,可能会丢失自己独有的方法

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

    Person obj = new Student();
    Student student = (Student)obj;
    student.study();
    
  4. 方便方法的调用,减少重复的代码

posted @ 2022-08-03 18:33  每年桃花开的时候  阅读(29)  评论(0)    收藏  举报