Inheritance and Polymorphism

inherit

The concept of inheritance

Inheritance is a cornerstone of Java object-oriented programming techniques because it allows the creation of hierarchical classes.

Inheritance means that the subclass inherits the characteristics and behavior of the parent class, so that the subclass object (instance) has the instance domain and methods of the parent class, or the subclass inherits the methods from the parent class, so that the subclass has the same behavior as the parent class.

Why use inheritance

When we define multiple classes with the same attributes and behaviors, the code is duplicated, resulting in a large amount of code, bloated, and low maintainability (maintainability is mainly when it needs to be modified later, and a lot of code needs to be modified. , easy to get out

Wrong), so to fundamentally solve the problem of these two pieces of code, we need to inherit and extract the same part of the two pieces of code to form a parent class.

Inherited spelling

Keywords (extends)

public Class A extends B {}

Where A is called a subclass, subclass, extended class or derived class, and B is called a superclass, parent class or base class

parent class and child class

1. Unlike traditional understanding, a subclass is not a subset of the parent class. In fact, a subclass usually contains more information and methods than its superclass.

2. The private data fields in the parent class are not accessible outside the class. Therefore, it cannot be used directly in subclasses. However, if public accessors/modifiers are defined in the parent class, they can be accessed and modified through these public accessors/modifiers.

3. Inheritance is used to model (is-a). Don't blindly extend a class just to reuse methods. For example: Although the Person class and the Tree class can share common properties like height and weight, it makes no sense to extend the Tree class from the Person class. A parent class and its child classes must have an (is-a) relationship.

4. Some programming languages ​​allow a subclass to be derived from several classes. This capability becomes multiple inheritance. But multiple inheritance is not allowed in java. A java class can only inherit from one parent class. This restriction is called single inheritance. In addition, java multiple inheritance can be achieved through interfaces.

super keyword

The keyword super refers to the parent class and can be used to call the common methods and constructors in the parent class.

call the constructor

Constructor methods are used to construct an instance of a class. Unlike properties and ordinary methods, constructors of parent classes are not inherited by child classes. They can only use the super keyword to call the super class constructor.

In the constructor of the subclass, the no-argument constructor of the parent class can be called through super(), or the constructor of the parent class that matches the parameters can be called through super(arguments).

super() and super(arguments) must appear on the first line of the subclass constructor, this is the only way to explicitly call the superclass constructor 

Constructor chain

class A {
    public A() {
        System.out.println ( " Constructor of A! " );
    }
}

class B extends A {
    public B() {
        System.out.println ( " Constructor of B! " );
    }
}

class C extends B {
    public C() {
        System.out.println ( " C 's constructor! " );
    }
}

public class test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        C c = new C();
    }

}

In the above code, C inherits B, and B inherits A. At this time, when an object c is instanced, what will happen? The result is as follows

A's construction method!
The construction method of B!
Constructor of C!

In the code, we did not call the super keyword, why is there such a result?

In any case, when an instance of a class is constructed, the constructors of all parent classes along the inheritance chain will be called. When constructing an object of a subclass, the subclass constructor will first call its superclass constructor before completing its own task. If the parent class inherits other classes, then the parent class constructor will call its own parent class constructor before completing its own task. This process continues until the last constructor along this inheritance architecture is called. This is called constructor chaining.

That is:

class B extends A {
    public B() {
        System.out.println ( " Constructor of B! " );
    }
}

class C extends B {
    public C() {
        System.out.println ( " C 's constructor! " );
    }
}

Equivalent to

class B extends A {
    public B() {
        super();
        System.out.println( "B's constructor!" );
    }
}

class C extends B {
    public C() {
        super();
        System.out.println( "Constructor of C!" );
    }
}

In addition to calling the constructor of the parent class, the super keyword can also call the ordinary method of the parent class: super.method name(parameter);

method overriding

Subclasses inherit methods from parent classes. Sometimes a subclass needs to modify the implementation of a method defined in the superclass, this is called method overriding.

To override a method, you need to define the method in the subclass with the same method name and the same return type as the superclass.

When the method of the parent class is overridden, if you want to access the method in the child class, you can also use the super keyword to call.

Notice:

1. An instance method can only be overridden if it is accessible. Because a private method is not accessible outside of its class itself, it cannot be overridden. If the method defined in the subclass is private in the superclass, then the two methods are completely irrelevant.

2. Like instance methods, static methods can also be inherited. However, static methods cannot be overridden. If the static method in the parent class is redefined in the child class, then the static method defined in the parent class will be hidden. The syntax can be used:

Parent class name. Static method name to call hidden static method

 difference between overriding and overloading

1. Method overriding occurs in different classes related by inheritance; method overloading can occur in the same class or in different classes related by inheritance.

2. Method overriding has the same method name and return value type; method overloading has the same name, but a different parameter list.

Object class and its toString() method

All classes in java inherit from the java.lang.Object class, that is, if no inheritance is specified when a class is defined, then the parent class of this class is defaulted to Object.

toString() method in Object class

public String toString()

Calling an object's toString() method returns a string describing the object. By default, it returns a string consisting of the class name to which the object belongs, the @ symbol, and the memory address of the object in hexadecimal form.

This information is not very useful. Typically, this method should be overridden so that it returns a descriptive string representing the object.

polymorphism

The three premises of polymorphism

1. There is an inheritance relationship

B,C,D inherit A

2. The subclass must override the method of the superclass (this is also the disadvantage of polymorphism, that is: you cannot use the subclass-specific member properties and subclass-specific member methods.)

3. The reference of the parent class data type points to the child class object.

A b = new B();

A c = new C();

A d = new D();

 

dynamic binding

Methods can be implemented in multiple classes along the inheritance chain. The JVM decides which method to call at runtime

Declared Type and Actual Type

A b = new B();

A variable must be declared as a certain type. This type of a variable is called its declared type, where b's declared type is A.

Instances can be created using the constructor of the declared type or its subtypes. The actual type of the variable is the actual class of the object referenced by the variable, where the actual type of b is B

The mechanism of dynamic binding

Suppose object o is an instance of classes C1, C2, C3, ..., Cn-1, Cn, where C1 is a subclass of C2, C2 is a subclass of C3, ..., Cn-1 is a subclass of Cn . If the o object calls a method p, the JVM will look for the method p in the classes C1, C2, C3..., Cn-1, Cn in turn, until it is found. Once found, stop looking and call this method.

 

An example of in-depth understanding of java polymorphism

https://blog.csdn.net/thinkGhoster/article/details/2307001

The priority of method calls, the priority is from high to low: this.show(O), super.show(O), this.show((super)O), super.show((super)O)

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325071289&siteId=291194637