0
点赞
收藏
分享

微信扫一扫

java-多态

往复随安_5bb5 2022-03-22 阅读 96
java

一、多态性polymorphism

1多态:一个类或多个类中可以定义多个同名方法,这些方法名称相同,操作不同。

2.多态性:在运行时系统判断应该执行哪个方法的能力。

3.分类:

(1)静态多态(编译时多态):方法重载实现,即一个类中定义多个同名方法,但参数列表不同。

(2)动态多态(运行时多态):方法覆盖实现,即在子类中定义与超类中方法名,返回值,参数都相同的方法。

二、方法绑定

1.定义:将一个方法调用与一个方法主体关联起来。

2.分类:前期绑定、后期绑定。java中除static方法和final方法都是后期绑定。

其实讲的就是调用方法的事情...

三、程序实例:

class Shape { 
  void draw() {}
  void erase() {} 
}

class Circle extends Shape {
  void draw() { 
    System.out.println("Circle.draw()"); 
  }
  void erase() { 
    System.out.println("Circle.erase()"); 
  }
}

class Square extends Shape {
  void draw() { 
    System.out.println("Square.draw()"); 
  }
  void erase() { 
    System.out.println("Square.erase()"); 
  }
}

class Triangle extends Shape {
  void draw() { 
    System.out.println("Triangle.draw()"); 
  }
  void erase() { 
    System.out.println("Triangle.erase()");
  }
}

public class Shapes {
  public static Shape randShape() {
    switch((int)(Math.random() * 3)) {
      default:
      case 0: return new Circle();
      case 1: return new Square();
      case 2: return new Triangle();
    }
  }
  public static void main(String[] args) {
    Shape[] s = new Shape[9];
    // Fill up the array with shapes:
    for(int i = 0; i < s.length; i++)
      s[i] = randShape();
    // Make polymorphic method calls:
    for(int i = 0; i < s.length; i++)
      s[i].draw();
  }
}

一种(random)输出是:

Triangle.draw()
Square.draw()
Square.draw()
Circle.draw()
Square.draw()
Circle.draw()
Square.draw()
Square.draw()
Circle.draw()
不再赘述解释

参考资料:

《java语言程序设计》——清华大学出版社

《java编程思想》——机械工业出版社

举报

相关推荐

Java-多态

Java-封装 继承 多态

Java-多态,接口详解

JAVA-继承和多态

Java-面向对象之多态

Java-多态的向上转型,向下转型

JAVA-概述

0 条评论