Current location - Quotes Website - Signature design - Why do I feel that polymorphism is useless in java. Let me give you an example.
Why do I feel that polymorphism is useless in java. Let me give you an example.

The benefits that polymorphism brings to us can be summarized into the following five points:

1. Substitutability. Polymorphism enables replacement of existing code. For example, polymorphism works for the Circle class, but it also works for any other circular geometry, such as a torus. As shown in Figure 8.1.

() Figure 8.1 Replacement

2. Extensibility. Polymorphism makes code extensible. Adding new subclasses does not affect the polymorphism, inheritance, and operation and operation of other features of existing classes. In fact, it is easier to add new subclasses to obtain polymorphic functions. For example, after implementing the polymorphisms of cones, semicones, and hemispheres, it is easy to add polymorphisms of the sphere class. As shown in Figure 8.2.

() Figure 8.2 Scalability

3. Interface-ability. Polymorphism is achieved by the superclass providing a unique interface to the subclass through method signatures, and the subclass can complete or override it. As shown in Figure 8.3. The super class Shape in the figure specifies two interface methods that implement polymorphism, computeArea() and computeVolume(). Subclasses, such as Circle and Sphere, improve or override these two interface methods in order to achieve polymorphism.

Figure 8.3 Polymorphic interface

4. Flexibility. It embodies flexible and diverse operations in applications and improves usage efficiency.

5. Simplicity. Polymorphism simplifies the code writing and modification process of application software. This feature is particularly prominent and important when dealing with calculations and operations on a large number of objects.

It is worth noting that polymorphism cannot solve the problem of increasing execution speed because it is based on dynamic loading and address reference, or dynamic binding. But in Java, except for final classes and final methods under certain conditions, all methods are dynamically bound by the JVM during runtime.