Java ~ inheritance and polymorphism

Posted by rivasivan on Fri, 25 Feb 2022 17:06:17 +0100

catalogue

inherit

Concept of inheritance

Inherited syntax

Access to parent class members

super keyword

The difference between super and this

Execution order and inheritance mode of inheritance relationship

Polymorphism

Implementation conditions of polymorphism

rewrite

The difference between rewriting and overloading

Upward and downward transformation

Advantages and disadvantages of polymorphism

inherit

Java uses classes to describe entities in the real world. The objects generated by instantiation of classes can be used to represent entities in the real world. When defining a class, if you encounter parts of two classes with the same attributes or functions, you can consider extracting the same parts of the two classes, which is inheritance in the idea of object-oriented. Inheritance is used to extract commonness and realize code reuse.

Suppose the following two classes are defined. These two classes have many common attributes and functions: name, age, sex, eat(), sleep()

Concept of inheritance

Inheritance mechanism: it is the most important means for object-oriented programming to make code reusable. It allows programmers to expand and add new functions on the basis of maintaining the characteristics of the original class. The new class produced in this way is called derived class. Inheritance presents the hierarchical structure of object-oriented programming and embodies the cognitive process from simple to complex. The main problem of inheritance is to extract commonness and realize code reuse.

According to the inheritance mechanism, the same parts of Cat class and Dog class are extracted to implement a new class - "Animal class". At this time, both Cat class and Dog class inherit Animal class, which is the idea of inheritance.

Among them, the Animal class is called: parent class / base class / super class, and the Dog class and Cat class are called the subclass / derived class of Animal. After inheritance, the subclass can reuse the members in the parent class, and the subclass only needs to pay attention to the new members it needs to add when implementing.

Inherited syntax

The inheritance relationship of classes in Java needs to be realized with the help of the extends keyword. The syntax format is as follows:

Modifier  class Subclass extends Parent class{
    //...
}

For example:

//Dog class is a subclass / derived class of Animal class
class Dog extends Animal{
    public void bark(){
        System.out.println(this.name + "Woof~");
    }
}

//Cat class is a subclass / derived class of Animal class
class Cat extends Animal{
    public void mew(){
        System.out.println(this.name + "Meow meow~");
    }
}

//The Animal class is the parent / base / superclass of Cat class and Dog class
public class Animal {
    public String name;
    public int age;
    public String sex;

    public void eat(){
        System.out.println(this.name + "be at  table");
    }

    public void sleep(){
        System.out.println(this.name + "sleeping");
    }
}

Access to parent class members

Access the member variable of the parent class in the subclass method

When the same member variable as the parent class does not exist in the subclass, you can directly access the member variable of the parent class in the subclass

When the accessed member variable exists in both the subclass and the parent class, the member variable of the subclass is accessed first, that is, the member variable of the subclass masks the member variable of the parent class. The access of member variables follows the principle of proximity. If you have one, you will have priority to access your own, and if you don't, you will find it in the parent class.

Access member methods of the parent class in a subclass

When accessing a method with a different name between a parent class and a child class through a child class object, first look for it in the child class and access it if found. Otherwise, look for it in the parent class and access it if found, otherwise an error will be reported;

When accessing a method with the same name of a parent class and a child class through a subclass object, if the parameter list of the method with the same name of the parent class and the child class is different, select the appropriate method to access according to the transfer of the calling method. If the appropriate method is not found, an error will be reported; If the prototypes of the methods with the same name of the parent class and the child class are consistent, only the methods of the child class can be accessed, and the methods in the parent class cannot be accessed directly through the derived class object.

For example, the following code

//Derived.java
public class Derived extends Base{
    int c = 10;
    int a = 5;
    public void method(){
        System.out.println("a = " + a + " b = " + b + " c = " + c);
    }
}
//Base.java
public class Base {
    int a = 10;
    int b = 5;
}

//Test.java
public class Test {
    public static void main(String[] args) {
        Derived test = new Derived();
        test.method();
    }
}

Output results

a = 5 b = 5 c = 10

According to the output results, it can be seen that when executing the method method, the a in the subclass is actually output. How can we access the member variables of the parent class in the subclass method? Using super keyword

super keyword

The super keyword is used to access the parent class member in the subclass method

For example:

//Derived.java
public class Derived extends Base{
    int c = 10;
    int a = 5;
    public void method(){
        //Access parent class member variables through super
        System.out.println("a = " + super.a + " b = " + b + " c = " + c);
        print();
        //Access parent class member methods through super
        super.print();
    }
    public void print(){
        System.out.println("Derived class");
    }
}
//Base.java
public class Base {
    int a = 10;
    int b = 5;
    public void print(){
        System.out.println("Base class");
    }
}
//Test.java
public class Test {
    public static void main(String[] args) {
        Derived test = new Derived();
        test.method();
    }
}

Output results

a = 10 b = 5 c = 10
Derived class
Base class

The above example shows the usage of the super keyword: in the subclass method, access the member methods and variables of the parent class

matters needing attention

1.super keyword can only be used in non static methods;

2. In the subclass method, access the member variables and methods of the parent class

Usage of super keyword

super.data: access parent class member variables;

super.func(): access the member method of the parent class;

super(): call the constructor of the parent class, which must be placed in the first line

The difference between super and this

For the description of this keyword, you can browse this link: Understanding of this keyword

super and this keywords can be used in member methods to access member variables and call other member functions. What's the difference between them?

Similarities:

1. It can only be used in non static methods to access non static member methods and fields;

2. when calling in a construction method, it must be the first statement in the construction method, and this and super can not exist at the same time.

difference:

1.this is a reference to the current object, and super is a reference to some members inherited from the parent class of the subclass object;

2. In non static member methods, this is used to access the methods and properties of this class, and super is used to access the methods and properties inherited from the parent class;

3.this is the hidden parameter of the non static member method, and super is not the hidden parameter;

4. In the construction method, this(...) Used to call the constructor of this class, super(...) It is used to construct the parent class construction method. The two calls cannot appear in the construction method at the same time;

5. There must be super(...) in the construction method Call (the compiler will automatically generate it if you don't write it yourself), but this(...) doesn't necessarily exist Call of (unless you write this call yourself)

6. When directly accessing the members of this class in the member method, this will be restored after compilation. All non static members of this class are accessed through this; Super is used to access parent class members in subclasses. After compilation, super does not exist at bytecode level

Execution order and inheritance mode of inheritance relationship

Execution order on inheritance relationship

1. The execution order of the static code block of the parent class takes precedence over that of the static code block of the child class, and is the earliest to be executed;

2. Then execute the parent class instance code block and construction method;

3. Then execute the instance code block and construction method of the subclass;

4. When the subclass object is instantiated for the second time, the static code blocks of the parent and subclass will not be executed again, but only once

Inheritance methods supported in Java

Java only supports single inheritance, multi-layer inheritance and different classes inherit the same class, but does not support multiple inheritance  

Polymorphism

After a method is called through a reference, it can be expressed in many forms. This idea is called polymorphism.

Implementation conditions of polymorphism

1. It must be used under the inheritance system;

2. The subclass must override the method of the parent class;

3. Call the overridden method through the reference of the parent class

Embodiment of polymorphism: when passing different objects, the methods in the corresponding class will be called

rewrite

Override: override is a subclass's rewriting of the implementation process of non static, non private modification, non final modification, non constructor, etc. of the parent class. The return value and formal parameters cannot be changed

Notes for rewriting:

1. The method modified by final is called sealing method, which means that the current method cannot be rewritten;

2. Methods modified by static cannot be rewritten;

3. Methods modified by private cannot be rewritten;

4. The access modification permission of the subclass should be greater than or equal to the access modification permission of the parent class

The difference between rewriting and overloading

Method overloading is a polymorphic representation of a class, and method rewriting is a polymorphic representation of subclasses and superclasses

Static binding and dynamic binding

Static binding: when compiling, determine which method to call according to the actual parameter type passed by the user. Representative type: function overload;

Dynamic binding: when compiling, you cannot determine which method to call. You need to wait until the program runs

Upward and downward transformation

Upward transformation

Create a subclass object and use it as a parent object

Syntax format:

Parent object name = new Subclass type();
Animal dog = new Dog();

Timing of upward Transformation: direct assignment, method parameter transfer and method return

Advantages of upward Transformation: make the code implementation more simple and flexible;

The disadvantage of upward Transformation: you can't call methods specific to subclasses

Downward transformation

After upward transformation, a subclass object is used as a parent method, and the subclass method can no longer be called, but sometimes it may be necessary to call the subclass specific method. At this time: restore the parent class reference to a subclass object, that is, downward transformation.

Advantages and disadvantages of polymorphism

advantage:

1. It can reduce the "circle complexity" of the code and avoid using a large number of if else statements;

2. Strong scalability

Disadvantages:

The running efficiency of the code is reduced

Examples of polymorphic codes are as follows:

class Car {
    public void carOfName(){}
}

class Bmw extends Car {
    @Override
    public void carOfName(){
        System.out.println("BMW: bmw");
    }
}

class Audi extends Car {
    @Override
    public void carOfName() {
        super.carOfName();
        System.out.println("Audi: audi");
    }
}

class Benz extends Car{
    @Override
    public void carOfName() {
        super.carOfName();
        System.out.println("Benz: Benz");
    }
}

public class TestDemo {
    public static void printCar(Car car){
        car.carOfName();
    }

    public static void main(String[] args) {
        printCar(new Bmw());
        printCar(new Audi());
        printCar(new Benz());
    }
}

Operation results:

BMW: bmw
Audi: audi
Benz: Benz

 

 

Topics: Java Back-end