zoukankan      html  css  js  c++  java
  • 多态

    引言:多态是指程序中定义的引用变量所指向的具体类型和通过该引用变量发出的方法调用在编程时并不确定,而是在程序运行期间才确定,即一个引用变量倒底 会指向哪个类的实例对象,该引用变量发出的方法调用到底是哪个类中实现的方法,必须在由程序运行期间才能决定。因为在程序运行时才确定具体的类,这样,不 用修改源程序代码,就可以让引用变量绑定到各种不同的类实现上,从而导致该引用调用的具体方法随之改变,即不修改程序代码就可以改变程序运行时所绑定的具 体代码,让程序可以选择多个运行状态,这就是多态性。多态性增强了软件的灵活性和扩展性。

    多态性:发送消息给某个对象,让该对象自行决定响应何种行为。 通过将子类对象引用赋值给超类对象引用变量来实现动态方法调用。

    java 的这种机制遵循一个原则:当超类对象引用变量引用子类对象时,被引用对象的类型而不是引用变量的类型决定了调用谁的成员方法, 但是这个被调用的方法必须是在超类中定义过的,也就是说被子类覆盖的方法。

    定义的是父类,但是new 子类,方法调用时用的都是父类的方法(子类共同的方法),子类扩展的方法就完蛋了,不能用!

    父类Animal

     1 public class Animal {
     2 
     3     public String name;
     4     public String food;
     5     
     6     public Animal(String name, String food) {
     7         super();
     8         this.name = name;
     9         this.food = food;
    10     }
    11     public void eat(){
    12         System.out.println(name+"吃"+food);
    13     }
    14     public void sleep(){
    15         System.out.println(name+"睡觉");
    16     }
    17 }

    子类Tiger 和Rabbit :

    
    
    public class Tiger extends Animal{
    
        public Tiger(String name, String food) {
            super(name, food);
            // TODO Auto-generated constructor stub
        }
    }
    
    public class Rabbit extends Animal{
    
        public Rabbit(String name, String food) {
            super(name, food);
            // TODO Auto-generated constructor stub
        }
    }
     

    测试类1(方法重载):

     1 public class Test {
     2     public void check(Tiger t){
     3         t.eat();
     4         t.sleep();
     5     }
     6     public void check(Rabbit r){
     7         r.eat();
     8         r.sleep();
     9     }
    10       *
    11       *
    12       *
    13       *
    14       *
    15 如果继承Animal的子类还多的话,还要写好多check(参数)方法
    16 
    17 }

    测试类(多态):

    1 public class Test {
    2      public void check(Animal t){
    3         t.eat();
    4         t.sleep();
    5      }
    6 }

    主类main:

    public class Main {
        public static void main(String[] args) {
            Test t=new Test();
            t.check(new Rabbit("兔子", "草"));
            System.out.println("============");
            t.check(new Tiger("老虎", "肉"));
        }
    }
  • 相关阅读:
    python3+selenium框架设计04-封装测试基类
    python3+selenium框架设计02-自动化测试框架需要什么
    python3+selenium框架设计01-Page Object
    python3+selenium入门16-窗口截图
    python3+selenium入门15-执行JavaScript
    爬虫入门
    NLP整体流程的代码
    NLTK与NLP原理及基础
    NLTK词性标注解释
    [hdu4355]Party All the Time(三分)
  • 原文地址:https://www.cnblogs.com/maxinliang/p/2772887.html
Copyright © 2011-2022 走看看