zoukankan      html  css  js  c++  java
  • java 笔记(3)多态 容易理解

    多态的使用

    class A1{
        public void tell1(){
            System.out.println("A1 -- tell1");
        }
    }
    
    class B1 extends A1{
        public void tell1(){
            System.out.println("B1 -- tell2");
        }
    }
    
    class C1 extends A1{
        public void tell1(){
            System.out.println("C1 -- tell3");
        }
    }
    
    public class PolDemo02 {
    
        public static void main(String[] args) {
            say(new B1());
            say(new C1());
        }
        
        public static void say(A1 a){
            a.tell1();
        }
    }

    运行结果:

    B1 -- tell2
    C1 -- tell3

     

    代码分析:

    在类PolDemo02中,main()方法传递给say()方法:new B1()和new C1()。我们可以这样看:A1 a = new B1(),A1 a = new C1(),声明部分为父类,赋值部分为子类的这个对象a,在调用重写方法时,是调用的子类的方法。另外,a对象不存在子类的其它方法。

     

    多态产生必须有以下条件:
    1.必须有继承。

    2.必须有方法重写。

    3.必须是父类声明,实际是子类对象。(父类声明,子类实例化)

  • 相关阅读:
    20-存储过程
    21-事务
    18-触发器
    19-函数
    16-pymysql模块的使用
    17-视图
    CodeForces 1369B. AccurateLee
    CodeForces 1312D.Count the Arrays(组合数学)
    CodeForces 1362D. Johnny and Contribution
    CodeForces 1363F. Rotating Substrings
  • 原文地址:https://www.cnblogs.com/Timenow/p/6847102.html
Copyright © 2011-2022 走看看