JAVA inheritance and polymorphism

Keywords: Java Back-end

Inheritance is one of the most remarkable features of object-oriented. Inheritance is to derive a new class from an existing class. The new class can absorb the data properties and behaviors of the existing class and expand new capabilities

1, Concept of inheritance

That is, the subclass inherits the properties and behaviors of the parent class, so that the subclass object can directly have the same properties and behaviors as the parent class. Subclasses can directly access non private properties and behaviors in the parent class.
Benefits of inheritance

Improve code reusability (reduce code redundancy and reuse the same code).
It creates a relationship between classes.

Inherited format

With the extends keyword, you can declare that a subclass inherits another parent class. The definition format is as follows:

Class parent {...} class subclass extends parent {...}

It should be noted that Java is single inheritance. A class can only inherit one direct parent class, which is very similar to the real world, but the subclasses in Java are more powerful.
Code demonstration
Parent class

public class Pizza {

    String name;
    private double price;
    private String size;

    public void show(){
        System.out.println(name+" "+size+" "+price);

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public double getPrice() {
        return price;

    public void setPrice(double price) {
        this.price = price;

    public String getSize() {
        return size;

    public void setSize(String size) {
        this.size = size;


package com.autumn.lesson10;

 * @Author: autumn
 * @Date: 2021/10/25
public class BaconPizza extends Pizza{
    public void show() {
        super.setName("Bacon Pizza");



 Scanner sc = new Scanner(;
        while (true){
            System.out.println("Please enter the type of pizza produced: 1.Bacon, 2.seafood");
            int i = sc.nextInt();
            Pizza pizza = null;
            if (i==1){
                pizza = new BaconPizza();
            if (i==2){
                pizza= new SeafoodPizza();

Inheritance is actually a subclass. The same attributes and behaviors can be defined in the parent class, and the unique attributes and behaviors of subclasses are defined by themselves. In this way, the reuse of the same attributes and behaviors is realized, which improves code reuse.

2, Override and reload

Rewriting is a subclass's rewriting of the implementation process of the accessible methods of the parent class, and the return value and formal parameters cannot be changed.
The advantage of rewriting is that subclasses can define their own specific behavior as needed. That is, the subclass can implement the methods of the parent class as needed.

A rewritten method cannot throw a new check exception or an exception that is broader than the declaration of the rewritten method.
Overloading is in a class. The method names are the same, but the parameters are different. The return type can be the same or different.

Each overloaded method (or constructor) must have a unique list of parameter types.

The most common place is the overloading of constructors.

3. Polymorphism

Polymorphism is another important feature of object-oriented programming. It means that after the attributes and methods defined in the parent class are inherited by the subclasses, they can have different data types or show different behaviors, which makes the same attribute or method have different meanings in the parent class and its subclasses.

For object-oriented, polymorphism can be divided into compile time polymorphism and run-time polymorphism. Compile time polymorphism is static, which mainly refers to method overloading. It distinguishes different methods according to different parameter lists. After compilation, it will become two different methods, and there is no polymorphism at run time. Runtime polymorphism is dynamic, which is realized by dynamic binding, which is commonly known as polymorphism.

There are three necessary conditions for Java polymorphism: inheritance, rewriting and upward transformation. Only when these three conditions are met, developers can use unified logic implementation code to deal with different objects in the same inheritance structure, so as to perform different behaviors.
Inheritance: there must be subclasses and parent classes with inheritance relationship in polymorphism.
Override: a subclass redefines some methods in the parent class. When these methods are called, the subclass's methods will be called.
Upward Transformation: in polymorphism, you need to assign the reference of the subclass to the parent object. Only in this way can the reference call both the methods of the parent class and the methods of the subclass.

1) Create the Figure class. In this class, first define the size of the storage two-dimensional object, then define the construction method with two parameters, and finally add the area() method, which calculates the area of the object. The code is as follows:

public class Figure {
    double dim1;
    double dim2;
    Figure(double d1, double d2) {
        // Construction method with parameters
        this.dim1 = d1;
        this.dim2 = d2;
    double area() {
        // Used to calculate the area of an object
        System.out.println("The method of calculating the object area in the parent class has no practical significance and needs to be overridden in the child class.");
        return 0;

2) Create a Rectangle subclass inherited from the Figure class, which calls the constructor of the parent class and overrides the area() method in the parent class. The code is as follows:

public class Rectangle extends Figure {
    Rectangle(double d1, double d2) {
        super(d1, d2);

    double area() {
        System.out.println("Area of rectangle:");
        return super.dim1 * super.dim2;

3) Create a Triangle subclass inherited from the Figure class, which is similar to Rectangle. The code is as follows:

public class Triangle extends Figure {
    Triangle(double d1, double d2) {
        super(d1, d2);

    double area() {
        System.out.println("Area of triangle:");
        return super.dim1 * super.dim2 / 2;

4) Create a Test class. In the main() method of the class, first declare the variable figure of the figure class, then specify different objects for the figure variable, and call the area() method of these objects. The code is as follows:

public class Test {
    public static void main(String[] args) {
        Figure figure; // Declare variables of Figure class
        figure = new Rectangle(9, 9);
        figure = new Triangle(6, 8);
        figure = new Figure(10, 10);

5) Execute the above code and the output results are as follows:

Posted by sundru on Mon, 25 Oct 2021 00:32:19 -0700