Inheritance in Java (important knowledge points!)

1, Inherit

1. Concept

Inheritance mechanism: it is the most important means for object-oriented programming to make code reusable. It allows programmers to extend and add new functions on the basis of maintaining the characteristics of the original class, so as to produce new classes, called derived classes. Inheritance presents the hierarchical structure of object-oriented programming and embodies the cognitive process from simple to complex.
Inheritance mainly solves the problems of commonness extraction and code reuse.

For example, both dogs and cats are animals. Define a cat and a dog respectively. They are both animals. Let them inherit the animal class, then we can extract the common content, and then use the idea of inheritance to achieve sharing.

// Dog.java
public class Dog{
string name;
int age;
float weight;
public void eat(){
System.out.println(name + "I am eating");
}
public void sleep(){
System.out.println(name + "be sleeping");
}
void Bark(){
System.out.println(name + "Woof, woof~~~");
}
}
// Cat.Java
public class Cat{
string name;
int age;
float weight;
public void eat(){
System.out.println(name + "I am eating");
}
public void sleep()
{
System.out.println(name + "be sleeping");
}
void mew(){
System.out.println(name + "cat ~~~");
}
}

2. Grammar

In Java, if you want to express the inheritance relationship between classes, you need to use the extends keyword, as follows:

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

For the cat and dog scenario, we let both cat and dog inherit the automatic object class:

public class Animal{
String name;
int age;
public void eat(){
System.out.println(name + "I am eating");
}
public void sleep(){
System.out.println(name + "be sleeping");
}
}
// Dog.java
public class Dog extends Animal{
void bark(){
System.out.println(name + "Woof, woof~~~");
}
}
// Cat.Java
public class Cat extends Animal{
void mew(){
System.out.println(name + "cat ~~~");
}
}
// TestExtend.java
public class TestExtend {
public static void main(String[] args) {
Dog dog = new Dog();
// There are no member variables defined in the dog class. The name and age attributes must be inherited from the parent class Animal
System.out.println(dog.name);
System.out.println(dog.age);
// The eat() and sleep() methods accessed by dog are also inherited from Animal
dog.eat();
dog.sleep();
dog.bark();
}
}

matters needing attention:
1. Subclasses inherit member variables or member methods from the parent class to subclasses.
2. The subclass must contain member methods or member variables different from the parent class, reflecting the difference from the parent class, otherwise inheritance will lose its meaning.

3. Access to parent class members

(1) Accessing parent class member variables in subclasses

The first case: there is no member variable with the same name in the child class and parent class

public class Base {
    int a;
    int b;
}
public class Derived extends Base {
    int c;
    int d;

    public void method(){
        a=10;//The member variable a inherited from the parent class is accessed
        b=20;//Access the member variable b inherited from the parent class
        c=30;//Access is the subclass's own member variable c
        d=40;//Access is the subclass's own member variable d
    }
}

The second case: the child class and parent class member variables have the same name

public class Base {
    int a;
    int b;
}
public class Derived extends Base {
    int b;
    int c;

    public void method(){
        a=10;
        b=20;//Is b in the parent class or b in the child class accessed at this time?
        c=30;
        //d=40;  Compilation reports an error because the member variable D does not exist in both the subclass and the parent class
    }
}

matters needing attention:
When accessing a member variable in a subclass method or through a subclass object:
1. If there are member variables in the subclass of the accessed member variables, access your own member variables first.
2. If there is no member variable in the subclass of the accessed member variable, it is inherited from the parent class. If the parent class is not defined, an error will be reported during compilation.
3. If the accessed member variable has the same name as the member variable in the parent class, its own will be accessed first, that is, the child class hides the member with the same name in the parent class.

(2) Access parent class member methods in subclasses

The first case: there is no member method with the same name in the subclass and parent class

public class Base {
    public void methodA(){
        System.out.println("I am a member of the parent class method");
    }
}
public class Derived extends Base {
    public void methodB(){
        System.out.println("I am a subclass member method");
    }

    public void methodC(){
        methodA();//Access member methods inherited from the parent class
        methodB();//Access the subclass's own member methods
        //methodD();  Compilation error. There is no methodd method in the inheritance system
    }
}

The second case: a method with the same name exists in the subclass and parent class

public class Base {
    public void methodA(){
        System.out.println("I am a member of the parent class method methodA");
    }
    public void methodB(){
        System.out.println("I am a member of the parent class method methodB");
    }
}
public class Derived extends Base {
    public void methodA(int a){
        System.out.println("I am a subclass member method methodA");
    }

    public void methodB(){
        System.out.println("I am a subclass member method methodB");
    }

    public void methodC(){
        methodA(1);//The methodA method with parameters accesses the methods of subclasses
        methodA();//The parameterless methodA method accesses the method of the parent class
        methodB();//Directly access methodB and access the methods of subclasses
    }
}

matters needing attention:
1. When accessing a method with a different name in a parent class and a child class through a child class object or method, first find it in the child class and access it if found. Otherwise, find it in the parent class and access it if found. Otherwise, an error will be reported during compilation.
2. 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 an appropriate method to access according to the parameters passed when calling the method. If not, an error will be reported; If the prototypes of methods with the same name of the parent class and the child class are consistent, only those of the child class can be accessed, and those of the parent class cannot be accessed directly through the derived class object.

Huh? What???? So the question is, how do you access the parent method with the same name as the child method and consistent with the prototype—— super keyword

4. super keyword

When there is a method with the same name and the same prototype in the subclass and parent class, we find that it cannot be accessed directly when we want to call the method of the parent class. In Java, we provide the super keyword, which is mainly used to access the members of the parent class in the subclass method.

public class Base {
    int a;
    int b;

    public void methodA(){
        System.out.println("I am a member of the parent class method methodA");
    }
    public void methodB(){
        System.out.println("I am a member of the parent class method methodB");
    }
}
public class Derived extends Base {
    int a;//Member with the same name as parent class
    String b;//The type of member with the same name as the parent class is different

    // Overload with methodA() in the parent class
    public void methodA(int a){
        System.out.println("I am a subclass member method methodA");
    }
    //Override the methodB method in the parent class
    public void methodB(){
        System.out.println("I am a subclass member method methodB");
    }

    public void methodC(){
        a=100;
        super.a=110;
        b="abc";
        super.b=100;

        methodA(1);//The methodA method with parameters accesses the methods of subclasses
        methodA();//The parameterless methodA method accesses the method of the parent class
        methodB();//Directly access methodB and access the methods of subclasses
        super.methodB();//methodB of the parent class is called through the super keyword
    }
}

Note: 1. It can only be used in non static methods.

2. Used in subclass methods to access member variables and methods of the parent class.

5. Subclass construction method

When constructing subclass objects, you need to call the base class construction method first, and then execute the subclass construction method.

public class Base {
   public Base(){
       System.out.println("I am the parent class constructor");
   }
}
public class Derived extends Base {
    public Derived(){
        // super();
        // Note that the subclass constructor will call the parameterless constructor of the base class by default: super()
        //The compiler automatically adds when the user does not write
        //And super() must be the first statement and can only appear once
        System.out.println("I am a subclass constructor");
    }

    public static void main(String[] args) {
        Derived a=new Derived();
    }
}
/*
results of enforcement
 I am the parent class constructor
 I am a subclass constructor
*/

Note: in the subclass construction method, no code about the construction of the base class is written, but when constructing the subclass object, the construction method of the base class is executed first, and then the construction method of the subclass is executed, because the subclass object is a parent object. When constructing the subclass object, the members inherited from the parent class must be initialized completely first, Then initialize the newly added members of the subclass.
From an object model perspective:

matters needing attention:
1. If the parent class explicitly defines a parameterless or default constructor, the compiler will generate a default constructor for the subclass, and there is an implicit super() call in the first line of the subclass constructor by default, that is, calling the base class constructor.
2. If the parent class construction method has parameters, the compiler will not generate the default construction method for the subclass. At this time, the user needs to explicitly define the construction method for the subclass and select the appropriate parent class construction method call in the subclass construction method, otherwise the compilation fails.
See the following code for details:

public class Base {
    int a;
    int b;
   public Base(int a){ //Construction method with parameters in parent class
       this.a=a;
   }
}
public class Derived extends Base {
    public Derived(int a,int b){ //At this time, you need to customize the construction method in the subclass
        super(a);//Select the appropriate parent class to construct the method call
        this.b=b;
    }

    public static void main(String[] args) {
        Derived a=new Derived(10,20);
        System.out.println(a.a);
        System.out.println(a.b);
    }
}

/*
Execution results:
10
20
 */

3. In the subclass constructor, when super(...) calls the parent class constructor, it must be the first statement in the subclass constructor.
4. super(...) can only appear once in a subclass constructor and cannot appear at the same time as this.

6. super and this

Similarities:
1. Are keywords in Java
2. It can only be used in non static methods of a class to access non static member methods and fields
3. When calling in a construction method, it must be the first statement in the construction method and cannot exist at the same time, as shown in the following figure:

difference:
Give me a piece of code first

public class Base {
    int a;
    int b;
}
public class Derived extends Base {
    int c;
    int d;
    public void method(){
        super.a=10;
        super.b=20;

        this.c=30;
        this.d=40;
    }
    public static void main(String[] args) {
        Derived d=new Derived();
        d.method();
    }
}

1. this is the reference of the current object. The current object is the object that calls the instance method. super is equivalent to the reference of the parent object. For the above codes, see the following figure:

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. The above figure can also be explained.
3. This is a hidden parameter of a non static member method, and super is not a hidden parameter. For the above code, from the perspective of bytecode, open the local variable table in the method method and find that there is only this but no super.

4. When directly accessing members of this class in member methods, this will be restored after compilation, that is, non static members of this class are accessed through this; In the subclass, if the parent class member is accessed through super, super does not exist at the bytecode level after compilation.

5. In the construction method: this(...) is used to call the construction method of this class, and super(...) is used to call the construction method of the parent class. The two calls cannot appear in the construction method at the same time.
6. There must be a call to super(...) in the constructor. If the user does not write, the compiler will increase, but if the user does not write this(...), it will not.

7. Code block execution order

The first is the execution order when there is no inheritance relationship

public class Person {
    int age;
    String name;

    public Person(int age,String name){
        this.age=age;
        this.name=name;
        System.out.println("Execution construction method");
    }
    {
        System.out.println("Execute instance code block");
    }

    static {
        System.out.println("Execute static code block");
    }

    public static void main(String[] args) {
        Person a=new Person(20,"luka");
        System.out.println("-----------------------");
        Person b=new Person(21,"stepth");
    }
}
/*
Execution results:
Execute static code block
 Execute instance code block
 Execution construction method
-----------------------
Execute instance code block
 Execution construction method
 */

explain:
1. The static code block is executed first and only once in the class loading phase
2. When an object is created, the instance code block will be executed. After the instance code block is executed, the construction method will execute
The second is the execution order when there is an inheritance relationship

public class Person {
    int age;
    String name;

    public Person(int age, String name) {
        this.age = age;
        this.name = name;
        System.out.println("Person:Execution construction method");
    }

    {
        System.out.println("Person:Execute instance code block");
    }

    static {
        System.out.println("Person:Execute static code block");
    }
}
public class Student extends Person{
    public Student(int age,String name){
        super(age,name);
        System.out.println("Student:Execution construction method");
    }
    {
        System.out.println("Student:Execute instance code block");
    }
    static{
        System.out.println("Student:Execute static code block");
    }

    public static void main(String[] args) {
        Student a=new Student(20,"luka");
        System.out.println("------------------------");
        Student b=new Student(21,"stepth");
    }
}
/*
Execution results:
Person:Execute static code block
Student:Execute static code block
Person:Execute instance code block
Person:Execution construction method
Student:Execute instance code block
Student:Execution construction method
------------------------
Person:Execute instance code block
Person:Execution construction method
Student:Execute instance code block
Student:Execution construction method
 */

explain:
1. The static code block of the parent class takes precedence over the static code block of the child class, and the static code block is the earliest to be executed compared with others.
2. The parent instance code block and the parent constructor are executed immediately.
3. The subclass instance code block and subclass construction method are then executed.
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 (the static code block will be executed only once).

8. Visibility of parent class members in child classes

What is the visibility of members with different access rights in the parent class in the child class?

// In extend01 package
public class B {
private int a;
protected int b;
public int c;
int d;
}
// In extend01 package
// Subclasses in the same package
public class D extends B{
public void method(){
// super.a = 10; //  Compilation error. The private member of the parent class is not visible in the same package subclass
super.b = 20; // protected members in the parent class can be accessed directly in the same package subclass
super.c = 30; // public members in the parent class can be accessed directly in the same package subclass
super.d = 40; // Members modified by the default access permission in the parent class can be accessed directly in the same package subclass
}
}
// In extend02 package
// Subclasses in different packages
public class C extends B {
public void method(){
// super.a = 10; //  Compilation error. The private member in the parent class is not visible in different package subclasses
super.b = 20; // protected modified members in the parent class can be accessed directly in different package subclasses
super.c = 30; // Members decorated with public in the parent class can be accessed directly in different package subclasses
//super.d = 40; //  Members modified by default access rights in the parent class cannot be accessed directly in different package subclasses
}
}
// In extend02 package
// Classes in different packages
public class TestC {
public static void main(String[] args) {
C c = new C();
c.method();
// System.out.println(c.a); //  An error is reported during compilation. The private member in the parent class is not visible in other classes in different packages
// System.out.println(c.b); //  protected members in the parent class cannot be accessed directly in other classes in different packages
System.out.println(c.c); // public members in the parent class can be accessed directly in other classes in different packages
// System.out.println(c.d); //  The members modified by the default access permission in the parent class cannot be accessed directly in other classes in different packages
}
}

**Note: * * the private member variable in the parent class cannot be accessed directly in the child class at any time, but it is also inherited into the child class.

9. Inheritance mode

The following inheritance methods are supported in Java:

Single inheritance:

Multi level inheritance:

Different classes inherit the same class

Multiple inheritance is not supported

10. final keyword

The final key can be used to modify variables, member methods, and classes.

1. Modifies a variable or field to represent a constant (that is, it cannot be modified).

final int a = 10;
a = 20; // Compilation error

2. Decorated class: indicates that this class cannot be inherited.

final public class Animal {
...
}
public class Bird extends Animal {
...
}
// Compilation error

Open the source code of the String class normally used. You can see that it is modified by final and cannot be inherited.

3. Modification method: indicates that the method cannot be overridden.

11. Combination

Composition is also a way to express the relationship between classes, and it can achieve the effect of code reuse. Composition does not involve special syntax (keywords such as extensions), but only takes an instance of one class as a field of another class.
This is the difference between inheritance and composition.

//Brake type
class Brake{

}
//Car handles
class Handle{

}
//Tires
class Tire{

}

public class Bicycle {
    private Brake brake;    //The attributes and methods in the brake can be reused
    private Handle handle;  //The attributes and methods of the handlebar can be reused
    private Tire tire;      //Properties and methods in the tire can be reused
}

Author: luka.lh
over!!!

Tags: Java inheritance

Posted on Tue, 19 Oct 2021 00:43:40 -0400 by Jtech