Home  >  Article  >  Java  >  What are the benefits of using java polymorphism?

What are the benefits of using java polymorphism?

王林
王林forward
2023-04-29 12:31:061639browse

Benefits

1. The cost of using the class for class callers is further reduced. Polymorphism only requires knowing that an object has a certain method.

Encapsulation allows the caller of the class to not need to know the implementation details of the class.

Polymorphism allows the caller of a class to not even need to know the type of the class, but only needs to know that the object has a certain method.

2. The scalability is stronger. If you want to add a new shape, the cost of code modification using polymorphism is also relatively low.

For the caller of the class (drawShapes method), just create an instance of a new class, and the cost of modification is very low.

Example

class Cycle {
private String name = "Cycle";
 
public static void travel(Cycle c) {
System.out.println("Cycle.ride()" + c);
}
 
public String toString() {
return this.name;
}
}
 
class Unicycle extends Cycle {
private String name = "Unicycle";
public String toString() {
return this.name;
}
}
 
class Bicycle extends Cycle {
private String name = "Bicycle";
public String toString() {
return this.name;
}
}
 
class Tricycle extends Cycle {
private String name = "Tricycle";
public String toString() {
return this.name;
}
}
 
public class Demo1 {
public static void ride(Cycle c) {
c.travel(c);
}
public static void main(String[] args) {
Unicycle unicycle = new Unicycle();
Bicycle bicycle = new Bicycle();
Tricycle tricycle = new Tricycle();
ride(unicycle);
ride(bicycle);
ride(tricycle);
}
}

The above is the detailed content of What are the benefits of using java polymorphism?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete