[Java and C++] What is polymorphism

Wednesday morning, September 20, 2023

I encountered polymorphism when I was doing my homework today, but I felt that I still didn’t understand polymorphism well enough, so I studied it in depth.

However, I feel that the article I wrote is not complete enough. For example, I did not mention when it is appropriate to use polymorphism. I will write it down when I have time.


Table of contents


What is polymorphism

Polymorphism allows objects of different classes to respond differently to the same message (method).

In layman's terms, for the same function makeSound, the response of the Animal class object is to output "make a sound", the response of the Cat class object is to output "meow meow...", and the response of the Dog class object is to output "woof woof". ..."

Polymorphism enables a program to handle different types of data or objects in a general way without caring about their specific types.

In different programming languages, the implementation and syntax details of polymorphism may differ, but the core idea of ​​polymorphism is the same: allowing different types of objects to exhibit different behaviors under a unified interface .


Java

In Java, you can achieve polymorphism using the following methods:

Method Overriding

This is the most common way of implementing polymorphism. It allows subclasses to override parent class methods, so that when the same method name is called, different method bodies are executed based on the actual type of the object. To use method overriding, the subclass needs to override the method in the parent class and use @Overrideannotations to ensure that the method is overridden correctly.

class Animal {
    void makeSound() {
        System.out.println("动物发出声音");
    }
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("汪汪");
    }
}

class Cat extends Animal {
    @Override
    void makeSound() {
        System.out.println("喵喵");
    }
}

Interface

Java's interface allows different classes to implement the same interface and then reference objects through the interface, thus achieving polymorphism. Different classes can implement methods in an interface in different ways.

interface Shape {
    void draw();
}

class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a circle");
    }
}

class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a rectangle");
    }
}

Abstract Class

Abstract classes can also be used to achieve polymorphism. Similar to interfaces, subclasses must implement the abstract methods in the abstract class.

abstract class Animal {
    abstract void makeSound();
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("汪汪");
    }
}

class Cat extends Animal {
    @Override
    void makeSound() {
        System.out.println("喵喵");
    }
}

Generics

Generics allow writing generic code to handle different types of data. By using generic type parameters, you can determine the type of an object at compile time and perform appropriate operations.


C++

In C++, there are two main ways to achieve polymorphism: virtual functions and function pointers.

However, virtual functions are the primary and recommended way to achieve polymorphism

Virtual Functions

In C++, member functions can be declared as virtual functions to achieve polymorphism. This is commonly used for inheritance and polymorphism in object-oriented programming. Virtual functions are implemented by declaring them in the base class and overriding them in the derived class. In this way, derived classes can provide their own implementations of virtual functions, and base class pointers or references can be used to call these virtual functions, depending on the type of the actual object.

class Animal {
public:
    virtual void makeSound() {
        std::cout << "动物发出声音" << std::endl;
    }
};

class Dog : public Animal {
public:
    void makeSound() override {
        std::cout << "汪汪" << std::endl;
    }
};

class Cat : public Animal {
public:
    void makeSound() override {
        std::cout << "喵喵" << std::endl;
    }
};

When using virtual functions, you can use base class pointers or references to achieve polymorphism. Which version of the function is executed depends on the type of the runtime object.

Function Pointers

In C++, you can also use function pointers to achieve polymorphism. A function pointer is a pointer to a function that can dynamically specify the function to be called. Polymorphism can be achieved using an array of function pointers or function pointer members to call different functions as needed.

class Animal {
public:
    void (*makeSound)() = nullptr;

    void playSound() {
        if (makeSound != nullptr) {
            makeSound();
        }
    }
};

void animalSound() {
    std::cout << "动物发出声音" << std::endl;
}

void dogSound() {
    std::cout << "汪汪" << std::endl;
}

int main() {
    Animal animal;
    animal.makeSound = animalSound;

    Animal dog;
    dog.makeSound = dogSound;

    animal.playSound(); // 调用 Animal 的声音函数
    dog.playSound();    // 调用 Dog 的声音函数

    return 0;
}

This approach allows the selection of functions to be called at runtime, but is more complex than virtual functions and requires manual management of function pointers.

To summarize, in C++, virtual functions are the main and recommended way to achieve polymorphism because it is easier to use and has better readability and maintainability. Function pointers can be used to implement polymorphism, but they are generally more suitable for specific advanced use cases, such as function callbacks. Virtual functions are the preferred way to achieve polymorphism in C++ .

Guess you like

Origin blog.csdn.net/m0_61629312/article/details/133087646