• 面向对象12:什么是多态


    什么是多态

    • 动态编译:类型:可扩展性

    • 即同一方法可以根据发送对象的不同而采用多种不同的行为方式。

    • 一个对象的实际类型是确定的,但可以指向对象的引用的类型有很多(父类或者有关系的类)

    • 多态存在的条件

      • 有继承关系
      • 子类重写父类方法
      • 父类引用指向子类对象
    • 注意:多态是方法的多态,属性没有多态性

    • instanceof (类型转换) 引用类型

    Application

    package com.oop;
    
    //import com.oop.demo04.Student;
    import com.oop.demo06.Student;
    import com.oop.demo06.Person;
    
    
    public class Application {
        public static void main(String[] args) {
            //一个对象的实际类型是确定的
            //new Student
            //new Person
    
            //可以指向的引用类型就不确定了;父类的引用指向子类
    
            //Student 能调用的方法都是自己的或者继承的父类的!
            Student s1 = new Student();
            //父类的引用可以指向子类,但是不能调用子类独有的方法
            Person s2 = new Student();
            Object s3 = new Student();
    
            s1.run();
            s2.run();
            //对象能执行哪些方法,主要看左边,和右边关系不大
            ((Student) s2).test();//s2.test();报错,父类在子类中只能引用自身存在的方法
            s1.test();
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    #Person

    package com.oop.demo06;
    
    public class Person {
        public void run(){
            System.out.println("run");
        }
    
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    Student

    package com.oop.demo06;
    
    public class Student extends Person{
        public void run(){
            System.out.println("run");
        }
        public void test(){
            System.out.println("test");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    注意事项:

    多态注意事项:
    1、多态是方法的多态,属性没有多态;
    2、父类和子类有联系 否则类型转换异常!CLassCastException!
    3、存在条件:继承关系,方法需要重写,父类引用指向子类对象! Father f1 = new Son();
    不能实现重写—>不能实现多态
    1、static属于类,不属于任何实例
    2、final 常量;
    3、private方法;

  • 相关阅读:
    com.google.gson.internal.LinkedTreeMap cannot be cast to XXX
    【支付宝生态质量验收与检测技术】
    图片怎么加水印?图片加水印用什么软件?
    宠物信息服务预约小程序的效果如何
    SpringBoot 1 SpringBoot 简介 1.1 SpringBoot 快速入门
    一次对pool的误用导致的.net频繁gc的诊断分析
    第一周pwn的题目
    uni-app使用iconfont字体图标
    数据挖掘与分析课程笔记(Chapter 1)
    SQL Server2019配置always on高可用图文步骤
  • 原文地址:https://blog.csdn.net/tianyi520jx/article/details/126214438