December 10, 2021

Java 多态

Java 多态

简介

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

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

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

优点

多态存在的必要条件

Java 多态实例

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
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();
}
}

输出:

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

形式

重载实现

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

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
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);

}
}

输出:

1
2
3
4
Find area
Circle area = 78.5
Triangle area=3.60
Rectangle area=12

重写实现

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
}
}

输出:

1
Car is running safely

多态性问题

About this Post

This post is written by OwlllOvO, licensed under CC BY-NC 4.0.

#JAVA