[JavaSE Column 63] Polymorphism, the parent class refers to the object of the subclass, an important concept in object-oriented programming

Author homepage : Designer Xiao Zheng
Author brief introduction : 3 years of JAVA full-stack development experience, focusing on JAVA technology, system customization, remote guidance, dedicated to enterprise digital transformation, certified lecturer of CSDN College and Blue Bridge Cloud Course.
Main direction : Vue, SpringBoot, WeChat applet

This article explains the concept and syntax of object-oriented polymorphism in Java, and gives sample codes. Polymorphism is an important concept in object-oriented programming, which allows the reference variable of the parent class to refer to the object of the subclass, and realizes the unified processing of objects of different subclasses.

insert image description here


1. What is polymorphism

Polymorphism is an important concept in object-oriented programming, which allows the reference variable of the parent class to refer to the object of the subclass, and realizes the unified processing of objects of different subclasses .

In Java, polymorphism can be achieved through inheritance and method overriding. When a parent class reference variable points to a subclass object, the overridden method in the subclass can be called through the parent class reference variable.

The advantage of polymorphism is that it can realize the calling and processing of different subclass objects through a unified parent class interface, which can improve the flexibility, scalability and maintainability of the code .

For example, suppose there is an animal class Animal and its two subclasses Dog and Cat.

There is a method in the Animal class eat(), and this method is rewritten in the Dog and Cat classes respectively.

Through polymorphism, you can use a reference variable of Animal type to refer to a Dog or Cat object, and then call a method through this reference variable eat(), and the program will automatically select the corresponding method to call according to the type of the actually referenced object.

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

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

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

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Animal animal1 = new Dog();
        Animal animal2 = new Cat();
        
        animal1.eat();  // 输出: Dog is eating.
        animal2.eat();  // 输出: Cat is eating.
    }
}

In the above example, animal1and animal2are reference variables of Animal type, but they point to Dog and Cat objects respectively. Although their type is Animal, the corresponding method will be called according to the type of object actually referenced at runtime, realizing polymorphism.

insert image description here


2. Why polymorphism

The existence of polymorphism in Java has the following 5 55 benefits, please study carefully.

  1. Flexibility : Polymorphism makes code more flexible and extensible. By using the reference variables of the parent class to refer to objects of different subclasses, different objects can be processed uniformly, thereby improving the flexibility of the code.
  2. Replaceability : Polymorphism makes code more replaceable. Since the parent class reference variable can refer to the object of the subclass, it can be replaced with a different subclass object without changing the code, thereby realizing the replaceability of the code.
  3. Uniform interface : Polymorphism makes the code have a unified interface. The interfaces and methods defined by the parent class can be shared in multiple subclasses, and these methods are called through the reference variables of the parent class, thereby realizing the unified interface of the code and making the program design more standardized and unified.
  4. Code reuse : Polymorphism realizes code reuse through the mechanism of inheritance. Subclasses can inherit the properties and methods of the parent class, thus avoiding repeated writing of the same code and improving code reusability.
  5. Extensibility : Polymorphism makes the code more extensible. By inheriting and rewriting the methods of the parent class, the subclass can expand the functions on the basis of the parent class and add new attributes and methods, thus realizing the extensibility of the code.

By properly applying polymorphism, we can design code with clear structure, extensibility and maintainability, and improve development efficiency and code quality. Polymorphism is an important feature in object-oriented programming, which can improve the flexibility and scalability of the code, and make the program design more in line with the object-oriented principle.

insert image description here


3. How to perform polymorphism

In Java, the basis of realizing polymorphism is inheritance and method rewriting. The following is a simple sample code to illustrate the realization of polymorphism. Please study carefully.

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

// 子类 Dog
class Dog extends Animal {
    
    
    @Override
    public void eat() {
    
    
        System.out.println("Dog is eating.");
    }
}

// 子类 Cat
class Cat extends Animal {
    
    
    @Override
    public void eat() {
    
    
        System.out.println("Cat is eating.");
    }
}

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Animal animal1 = new Dog(); // 父类引用指向子类对象
        Animal animal2 = new Cat(); // 父类引用指向另一个子类对象

        animal1.eat(); // 调用重写后的方法,输出:Dog is eating.
        animal2.eat(); // 调用重写后的方法,输出:Cat is eating.
    }
}

In the example above, Animal is the parent class, and Dog and Cat are the subclasses. There is a method in the parent class Animal eat(), and the subclasses Dog and Cat override this method respectively.

In the method of the Main class , refer to the Dog and Cat objects through the reference variables and main()of the Animal type .animal1animal2

animal1and animal2are reference variables of type Animal, but they actually point to Dog and Cat objects.

When calling animal1.eat()and animal2.eat(), since these two reference variables point to different subclass objects, the corresponding overridden method will be called according to the type of the actually referenced object.

This is the embodiment of polymorphism. The same method call can execute different implementations according to different object types , which realizes the flexibility and scalability of the code.

insert image description here


4. The relationship between polymorphism and encapsulation and inheritance

In Java, polymorphism, encapsulation and inheritance are three important features of object-oriented programming, and there is a close relationship and mutual support between them.

  1. Inheritance and polymorphism
  • Inheritance is to derive a new class from an existing class by creating a new class, and the new class inherits the properties and methods of the existing class. Subclasses can override the methods of the parent class to implement their own specific logic, which is the embodiment of polymorphism.

  • Polymorphism means that the same method call can execute different implementations according to different types of objects. Through inheritance and method rewriting, different subclass objects can be referenced in the parent class reference variable to realize unified processing of different objects.

  1. Encapsulation and inheritance
  • Encapsulation is to encapsulate data and methods in a class, hide implementation details from the outside, and only provide public interfaces for other classes to access.

  • Inheritance can inherit the properties and methods of the parent class, and the subclass can directly use the public interface of the parent class without knowing the specific implementation details, realizing the characteristics of encapsulation.

  1. Polymorphism and encapsulation
  • Polymorphism enables different subclass objects to call the same method through parent class reference variables through the interfaces and methods defined by the parent class.

  • Encapsulation encapsulates data and methods in a class, hides implementation details from the outside, and accesses class functions by providing a public interface. Polymorphism makes it unnecessary for external callers to care about the specific implementation, and only needs to use the public interface to call the method.

So polymorphism, encapsulation, and inheritance are three important features in object-oriented programming. They are interrelated and support each other, and together form the basis of object-oriented programming. Polymorphism is achieved through inheritance and method rewriting. Encapsulation protects data and methods by hiding implementation details. Inheritance reuses code and extends functions by inheriting the properties and methods of the parent class through subclasses.

insert image description here


Five, polymorphic interview questions

1. What is polymorphism?

Polymorphism is an important concept in object-oriented programming, which means that the same method call can perform different implementations according to different types of objects. Specifically, through inheritance and method rewriting, subclasses can rewrite parent class methods, and refer to objects of different subclasses through parent class reference variables to achieve unified processing of different objects.

2. What are the implementation methods of polymorphism?

In Java, polymorphism can be achieved in the following ways.

  • Inheritance : Subclasses inherit the properties and methods of the parent class, and can override the methods of the parent class to achieve different behaviors.
  • Method rewriting : subclasses can rewrite the method of the parent class, that is, redefine the implementation logic of the method in the subclass.
  • Interface implementation : A class implements one or more interfaces, and the method of the implementing class is called through the interface reference variable.

3. What are the benefits of state?

Polymorphism has several benefits.

  • Flexibility : Through polymorphism, the code is more flexible and extensible, and new objects can be replaced or added according to actual needs without changing the existing code.
  • Substitutability : Through polymorphism, the same parent class reference variable can refer to objects of different subclasses, realizing the replaceability of code.
  • Unified interface : Through polymorphism, you can define a unified interface and method, realize the unified operation of different objects, and improve the standardization and maintainability of the code.
  • Code reuse : Through inheritance and polymorphism, the properties and methods of the parent class can be reused, avoiding repeated writing of the same code.
  • Scalability : Through polymorphism, new properties and methods can be added to subclasses, which realizes the scalability of the code.

Fourth, please give an example of polymorphism.

A common example of polymorphism is the Animal class and its subclasses, such as Cat and Dog. You can define an Animal class as a parent class with a eat()method. Then define the cat class and dog class as subclasses, and rewrite eat()the methods respectively. Reference variables of the parent class to refer to objects of the cat and dog classes, and call eat()the method to achieve different behaviors of different animal objects.


6. Summary

This article explains the concept and syntax of object-oriented polymorphism in Java, and gives sample codes. In the next blog, I will explain the knowledge points of Java abstract classes and interfaces.

insert image description here

Guess you like

Origin blog.csdn.net/qq_41464123/article/details/132048421