Java 多态

2021 年 12 月 10 日 星期五(已编辑)
1
这篇文章上次修改于 2021 年 12 月 10 日 星期五,可能部分内容已经不适用,如有疑问可询问作者。

Java 多态

Java 多态

简介

Java有三大特性:封装、继承和多态

多态就是指程序中定义的引用变量所指向的具体类型和通过该引用变量发出的方法调用在编程时并不确定,而是在程序运行期间才确定,即一个引用变量倒底会指向哪个类的实例对象,该引用变量发出的方法调用到底是哪个类中实现的方法,必须在由程序运行期间才能决定。

因为在程序运行时才确定具体的类,这样,不用修改源程序代码,就可以让引用变量绑定到各种不同的类实现上,从而导致该引用调用的具体方法随之改变,即不修改程序代码就可以改变程序运行时所绑定的具体代码,让程序可以选择多个运行状态,这就是多态性。

优点

  • 消除类型之间的耦合关系
  • 可替换性
  • 可扩充性
  • 接口性
  • 灵活性
  • 简化性

多态存在的必要条件

  • 继承:在多态中必须要有子类继承父类的关系
  • 重写:子类要重写父类的方法,这样调用子类的方法才会调用子类的方法
  • 向上转型:父类引用指向子类对象 Parent p = new Child();

Java 多态实例

class Shapes {
  public void area() {
    System.out.println("The formula for area of ");
  }
}
class Triangle extends Shapes {
  public void area() {
    System.out.println("Triangle is ½ * base * height ");
  }
}
class Circle extends Shapes {
  public void area() {
    System.out.println("Circle is 3.14 * radius * radius ");
  }
}
class Main {
  public static void main(String[] args) {
    Shapes myShape = new Shapes();  // Create a Shapes object
    Shapes myTriangle = new Triangle();  // Create a Triangle object
    Shapes myCircle = new Circle();  // Create a Circle object
    myShape.area();
    myTriangle.area();
    myShape.area();
    myCircle.area();
  }
}

输出:

The formula for the area of Triangle is ½ * base * height
The formula for the area of the Circle is 3.14 * radius * radius

形式

重载实现

方法重载的定义是,可以在同一类中创建多个同名方法的过程,所有方法都以不同的方式工作。当类中有多个同名方法时,就会发生方法重载。

class Shapes {
  public void area() {
    System.out.println("Find area ");
  }
public void area(int r) {
    System.out.println("Circle area = "+3.14*r*r);
  }

public void area(double b, double h) {
    System.out.println("Triangle area="+0.5*b*h);
  }
public void area(int l, int b) {
    System.out.println("Rectangle area="+l*b);
  }


}

class Main {
  public static void main(String[] args) {
    Shapes myShape = new Shapes();  // Create a Shapes object
    
    myShape.area();
    myShape.area(5);
    myShape.area(6.0,1.2);
    myShape.area(6,2);
    
  }
}

输出:

Find area
Circle area = 78.5
Triangle area=3.60
Rectangle area=12

重写实现

当子类或子类具有与父类中声明的方法相同时,方法重写被定义为进程。

class Vehicle{  
  //defining a method  
  void run(){System.out.println("Vehicle is moving");}  
}  
//Creating a child class  
class Car2 extends Vehicle{  
  //defining the same method as in the parent class  
  void run(){System.out.println("car is running safely");}  
  
  public static void main(String args[]){  
  Car2 obj = new Car2();//creating object  
  obj.run();//calling method  
  }  
}

输出:

Car is running safely

多态性问题

  • 多态性在实施过程中相当具有挑战性。
  • 多态性往往会降低代码的可读性。
  • 多态性实时提出了一些严重的性能问题。

使用社交账号登录

  • Loading...
  • Loading...
  • Loading...
  • Loading...
  • Loading...