Exploring Polymorphism in Java: The King of Code Reuse

What is polymorphism in Java?

In Java, polymorphism (polymorphism) is a characteristic of an object that allows the behavior of the object to be changed without modifying the code. In simple terms, polymorphism means that the same method or operator has different implementation methods or results. This feature allows objects of one class to be regarded as objects of another class, thereby achieving code flexibility and reusability.

Polymorphism is an important concept in object-oriented programming and one of the basic concepts in Java programming. Its role is not only to make the code more flexible and avoid code duplication, but also to make the code easier to maintain and expand.

polymorphic implementation

Polymorphism in Java can be implemented in two ways:

1. Method overloading (Overload)

In Java, method overloading refers to the definition of multiple methods in a class that have the same name but differ in the type or number of parameters and can also include different return types. When calling a method, the compiler will match the correct method according to the type, quantity and order of the actual parameters, and call the corresponding method.

For example, suppose we have a class that calculates the area of ​​a graph, we can define the following three methods for this class:

public double getArea(double r) {
    // 计算圆的面积
}

public double getArea(double w, double h) {
    // 计算矩形的面积
}

public double getArea(double a, double b, double c) {
    // 计算三角形的面积
}

When we call the getArea method, the compiler will match the appropriate method according to the parameters passed in, for example:

double area1 = getArea(3.0); // 调用计算圆的面积的方法
double area2 = getArea(2.0, 3.0); // 调用计算矩形的面积的方法
double area3 = getArea(3.0, 4.0, 5.0); // 调用计算三角形的面积的方法

This is how method overloading achieves polymorphism.

2. Method rewriting (Override)

Method rewriting in Java means that a subclass redefines a method with the same assignment, return type, and name defined in the parent class. The subclass overrides the method in the parent class, so that when the method is called, the method in the subclass is actually called instead of the method in the parent class.

For example, let's assume that the parent class has a method called getPrice(), and its return value is a double type, which is used to obtain the price of an item. Now there is a subclass that needs to calculate the discounted price of the product, then the getPrice() method can be rewritten to achieve it.

class Product {
    public double getPrice() {
        // 获取商品价格
    }
}

class DiscountProduct extends Product {
    public double getPrice() {
        // 计算打折价格
    }
}

When we call the getPrice method of DiscountProduct, the method in the subclass is actually called instead of the method in the parent class. This is how method overriding achieves polymorphism.

Polymorphic Application Scenarios

Polymorphism can improve code scalability and maintainability. In Java, polymorphism is often used in the following ways:

1. Inheritance

Inheritance is the prerequisite for polymorphism. The subclass inherits the parent class, rewrites the method in the parent class in the subclass, and realizes the polymorphism of the method.

class Animal {
    public void eat() {
        System.out.println("Animal is eating");
    }
}

class Dog extends Animal {
    public void eat() {
        System.out.println("Dog is eating");
    }
}

In this example, the Dog class inherits the Animal class and overrides the eat method. When we call the eat method of Dog, the eat method in Dog is actually called.

2. Interface

Interfaces are also capable of polymorphism. Methods defined in an interface can be implemented in different ways by classes implementing the interface. In this way, when using objects of these classes, we can use the type of the interface to refer to them and call the methods it implements.

interface Flyable {
    void fly();
}

class Bird implements Flyable {
    public void fly() {
        System.out.println("Bird is flying");
    }
}

class Plane implements Flyable {
    public void fly() {
        System.out.println("Plane is flying");
    }
}

In this example, the Bird and Plane classes both implement the Flyable interface and implement the fly method. When we call the fly method of Bird and Plane, we actually call the fly method implemented by them.

3. Generics

Java's generics can also achieve polymorphism. Generics can make a generic type have different methods and behaviors under different instantiation parameters.

class Generic<T> {
    public void print(T t) {
        System.out.println("Generic type: " + t.getClass().getName());
    }
}

In this example, we define a generic class Generic that can accept different type parameters. When we instantiate this class with different types, it behaves differently.

Generic<String> g1 = new Generic<>();
Generic<Integer> g2 = new Generic<>();
g1.print("Hello World"); // 输出Generic type: java.lang.String
g2.print(123); // 输出Generic type: java.lang.Integer

In this example, g1 is an instantiated Generic class whose type parameter is String. When we call its print method, it will output "Generic type: java.lang.String". Similarly, the type parameter of g2 is Integer, and when we call its print method, it will output "Generic type: java.lang.Integer".

Advantages of polymorphism

Polymorphism has many advantages in object-oriented programming, as follows:

1. Improve code reusability

Polymorphism separates the implementation of the method from the specific implementation, which improves the reusability of the program. We only need to rewrite the method when needed, and provide new functions for the program without affecting the original function of the program.

2. Improve code scalability

Polymorphism allows a class to interact with other different classes, making the program more scalable.

3. Make programs easier to maintain

Polymorphism can make the modules in the program more independent. When a function needs to be modified, only the implementation of the function needs to be modified without affecting other parts of the program.

4. Make the program more flexible

Polymorphism allows us to determine which method or object to use at runtime, making the program more flexible.

Summarize

Polymorphism is an important concept in Java, which can be realized through method overloading, method rewriting, interface and generics. Polymorphism can improve the scalability, reusability, maintainability and flexibility of the program, making the program more robust and elastic. In actual development, polymorphism is a very important programming idea, which requires us to understand and master it more deeply.

Guess you like

Origin blog.csdn.net/weixin_40986713/article/details/131093283