Home > Java > javaTutorial > body text

What are the benefits of using java polymorphism?

王林
Release: 2023-04-29 12:31:06
forward
1638 people have browsed it

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);
}
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template