[Learn JAVA from scratch | Article 14] Inheritance

Table of contents

Foreword: 

Introduce:

inherit:

Small expansion:

advantage:

 Inheritance of member methods:

Summarize:


Foreword: 

 Inheritance is one of the three major characteristics of object-oriented. It is an important property we explained after encapsulation. Inheritance is the relationship between classes. Subclasses will inherit the member functions and member methods of the parent class that are open to subclasses. This greatly optimizes the reusability when we write code, so we have to learn inheritance so that we can learn JAVA well

Introduce:

If we want to create a student class at this time, its member variables include name, age, gender, and member behaviors include eating, playing games, sleeping, and studying. To create a teacher class, its member variables include name, age, gender, and member behaviors include eating, playing games, sleeping, and teaching. We will build it like this before:

But we will find that, in fact, the behavior of these two classes is highly similar, so can we simplify it?
Here we use the inheritance we said before. We abstract a parent class to summarize the common points between these two classes, and then these two classes inherit the parent class, which will not reduce the reusability of the code.

 In fact, this is the idea of ​​inheritance : abstract the similarities between classes and create a parent class that can be inherited to reduce the reusability of code.

inherit:

In Java, inheritance is one of the important concepts in object-oriented programming. It means that a class can inherit the properties and methods of another class, and at the same time, it can add or override the functions of the parent class to create a new class. Through inheritance, subclasses can obtain all or part of the characteristics of the parent class, thereby reducing code duplication, simplifying program design, and improving code reusability.

In Java, a subclass inherits from a parent class through   the extends   keyword. Subclasses can access public and protected member variables and methods in the parent class , but cannot access private member variables and methods of the parent class . Subclasses can override parent class methods, implement their own specific behavior, or add new methods and properties.

Following is an example of simple Java class inheritance:

class Animal {
    String name;
    int age;
    void eat() {
        System.out.println("Animal is eating");
    }
}

class Cat extends Animal {
    void meow() {
        System.out.println("Cat is meowing");
    }
}

public class Test {
    public static void main(String[] args) {
        Cat cat = new Cat();
        cat.name = "Tom";
        cat.age = 2;
        cat.eat();
        cat.meow();
    }
}

In the above example, Catthe class inherits Animalthe class and adds a method of its own meow. In the main program, we create an Catobject of a class, and can access Animalthe properties and methods of the class, and can call Catthe class's own methods.

Small expansion:

The inheritance methods of JAVA and C++ are very similar, but in java, all inheritance is public inheritance, there is no protected inheritance and private inheritance

In Java, inheritance can be divided into public inheritance and protected inheritance .

Public inheritance means that subclasses can inherit the public members and protected members of the parent class, but cannot inherit the private members of the parent class.

Protected inheritance means that the subclass can inherit the public members and protected members of the parent class, but cannot directly access the private members of the parent class. (It’s just that it can’t be accessed directly, we will introduce the way to access later)

In fact, there is no need to declare the inheritance method in Java, and public inheritance is used by default. All member variables and methods in Java have an access modifier, such as public, private, and protected. By using different access modifiers, the access scope of subclasses can be limited. At the same time, Java provides some keywords, such as final and static, which can be restricted or defined during inheritance.

* Protected inheritance (JAVA)    is not      protected inheritance (C++)

Protected inheritance will inherit the private members of the parent class to the subclass, and the subclass cannot be accessed directly, but can be accessed indirectly

Protected inheritance will inherit all the members of the parent class to the subclass (private members are also inherited), but the subclass will not provide the function to call, which is equivalent to no inheritance.

If you don't believe it, we can call the vs 2022 administrator background to verify. The space here is limited, so we won't verify it.

How to access the private variables in the parent class in the subclass?

If you need to access the private variables of the parent class in the subclass, you can use the getter and setter methods provided in Java to implement it by calling the public methods of the parent class.

For example, we declare a private variable in the parent class:

public class Parent {
    private int x;
    public Parent(int x) {
        this.x = x;
    }
    private int getX() {
        return x;
    }
}

A public getter method getX() can be added to the parent class to obtain the value of the private variable x:

public class Parent {
    private int x;
    public Parent(int x) {
        this.x = x;
    }
    private int getX() {
        return x;
    }
    public int getPrivateVariableX() {
        return this.getX();
    }
}

Subclasses can obtain the value of the parent class's private variable x by calling the parent class's public method getPrivateVariableX():

public class Child extends Parent {
    public Child(int x) {
        super(x);
    }
    public int getPrivateVariableX() {
        return super.getPrivateVariableX();
    }
}

In this way, the private variable x in the parent class can be obtained and used in the subclass. However, it should be noted that private variables have restricted access rights in the parent class, and access through public methods in subclasses may cause access rights loopholes, so special attention is required.

advantage:

Inheritance is an important feature in object-oriented programming, which has the following advantages:

1. Code reuse: Through inheritance, the code and functions of existing classes can be reused in new classes, avoiding the waste of resources caused by repeated code writing, and improving the reusability of code.

2. The inheritance relationship reflects the real relationship in the program : the inheritance relationship can clearly express the relationship between the parent class and the subclass, thereby improving the readability and maintainability of the program.

3. Good scalability: through inheritance, you can easily extend a class and add new features without affecting existing code and existing functions.

4. Polymorphism: Through the polymorphic characteristics of inheritance and subclasses, the code can be made more flexible and extensible.

5. Code encapsulation: Inheritance provides a way of encapsulation. Members in the parent class can be reused in subclasses and are invisible to the outside world, ensuring code security and privacy.

In short, code reuse and extension can be realized relatively simply through inheritance, making the code more flexible, more readable, and improving the maintainability of the code.

At this point, many friends will fall into a misunderstanding : since inheritance is so convenient, we will abstract the parent class when creating multiple classes in the future, and then inherit the parent class to the subclass.

This thinking is wrong! This is because although inheritance is very convenient, our parent class should have a certain relationship with the subclasses. This is done to improve the readability of the code. For example, we abstract animals and inherit them to subclasses such as kittens and dogs, and abstract mobile phones to inherit subclasses such as Xiaomi, Huawei, and Apple . Instead of abstracting the parent class at will.

JAVA only supports single inheritance, does not support multiple inheritance, but supports multi-level inheritance.

Translation: A cannot inherit B and C at the same time (multi-inheritance is not supported). But C can inherit B, and A can inherit C (multi-level inheritance).

In fact, this feature is to solve the defects caused by multiple inheritance in C++ : if the method names of the two parent classes are similar, then if our subclass inherits these two parent classes, when calling this method, which parent class method do we call?
The answer given by c++ is virtual inheritance

Virtual inheritance refers to the use of the keyword virtual when inheriting. This inheritance method can avoid the ambiguity caused by derived classes inheriting members (data and functions) with the same name in multiple base classes . This is because virtual inheritance allows derived classes to keep only one unique base class subobject in their inheritance tree, thus eliminating duplicate inherited members.

For example, suppose there are two base classes A and B, both of which have a function f() with the same name, if a class C inherits A and B, then when calling C::f(), an ambiguity problem will occur. But if A and B are virtual inheritance, then class C only inherits one subobject of A and one subobject of B, so that C::f() will not be inherited repeatedly. If you need to call the f() function in A or B in C, you can use the scope parser (::) to specify the function to call a certain base class, and just specify the base class A or B when calling.

Here is a sample code:

class A {
public:
    virtual void f() {
        cout << "A::f()" << endl;
    }
};

class B {
public:
    virtual void f() {
        cout << "B::f()" << endl;
    }
};

class C: public virtual A, public virtual B {
public:
    virtual void f() {
        A::f(); // 调用A的f()函数
        B::f(); // 调用B的f()函数
    }
};

int main() {
    C c;
    c.f(); // 输出 A::f() B::f()
    return 0;
}

In order to avoid this cumbersome step, our JAVA directly prohibits the ability of subclasses to inherit multiple parent classes.

 In fact, every class will inherit Object directly or indirectly.

In Java, Object is the root class of all classes. The Java language is an object-oriented language, and all classes inherit the Object class directly or indirectly, so the Object class is very important and basic in Java programs.

The Object class defines some common methods, such as:

  • toString() method: used to return the string representation of the object, usually overridden by subclasses.
  • equals() method: used to compare whether two objects are equal.
  • hashCode() method: used to return the hash code of the object, usually overridden.

In addition, the Object class also defines some other commonly used methods, such as the getClass() method for obtaining the class of the object, and methods such as notify(), notifyAll(), and wait() for thread synchronization.

It should be noted that the Object type is a top-level type in Java, not a basic type. In Java, there are eight basic data types: byte, short, int, long, float, double, boolean, and char. Although the Object class is a very important class in Java, don't abuse the Object type, try to use specific subclasses, so that the program has better type safety and readability.

 Inheritance of member methods:

 If A to D is inherited layer by layer, then if we call method C in A, will he really find method D step by step in the parent class?

In fact, this is not the case. We have a virtual method table , and each parent class will add its own method to the virtual function table for quick query when calling.

The methods in the virtual method table must be:

  • Non-private: The method modified by the private keyword can only be accessed in this class and cannot be inherited by subclasses, so it cannot be a virtual method and will not be stored in the virtual method table.

  • Non-static: A static method belongs to a class rather than an object, and cannot be inherited by subclasses, so it cannot be a virtual method, nor will it be stored in the virtual method table.

  • Non-final: The method modified by the final keyword cannot be overridden by subclasses, so it is impossible to become a virtual method, and it will not be stored in the virtual method table.

It should be noted that in Java, the virtual method table is dynamically generated at runtime, based on the actual object type, not the declared type of the variable. This is an efficient way for Java to achieve polymorphism, which can enable programs to achieve runtime dynamic binding and improve code maintainability and scalability.

2. Problems with subclasses inheriting parent class constructors:

1. The subclass cannot inherit the constructor of the parent class, but it can be called by super

2. The first line of the subclass construction method must be a super(); this is because the member variables of the parent class may be used in the construction of the subclass. If the parent class is not constructed first and directly used in the construction of the subclass, errors may occur.

3. If you want super to call the parametric structure of the parent class, you must write it manually

Summarize:

Inheritance is the relationship between classes, and inheritance belongs to one of the three major characteristics of object-oriented, which is a very important property. Therefore, we must learn this knowledge point so that we can play JAVA well.

If my content is helpful to you, please like, comment and bookmark . Creation is not easy, everyone's support is my motivation to persevere!

Guess you like

Origin blog.csdn.net/fckbb/article/details/131343600