I am learning Java inheritance in VScode (what is Java inheritance, characteristics, what is subclass inheritance) 一

Java inheritance is an important concept in object-oriented programming, which allows a class (called a subclass or derived class) to inherit properties and behaviors from another class (called a parent or base class). Through inheritance, subclasses can reuse the existing code of the parent class, and can add new functions on this basis. [Subclass is a kind of parent class]

java inheritance

what is inheritance

In Java, extendsinheritance is implemented using keywords. A subclass is declared using extendsthe keyword followed by the name of the parent class. Subclasses inherit the non-private member variables and methods of the parent class, including fields, constructors, and methods.

Following is a simple example to illustrate the basic concept of inheritance in Java −

class Animal {
    
     // 父类
    protected String name;

    public void eat() {
    
    
        System.out.println("Animal is eating.");
    }
}

class Dog extends Animal {
    
     // 子类
    public void bark() {
    
    
        System.out.println("Dog is barking.");
    }
}

In the above example, the class is a base class in which one field and one method Animalare defined . A class is a derived class that inherits the attributes and behaviors of the class through keywords and adds a new method.nameeat()DogextendsAnimalbark()

We can create Dogan instance of a class and call its inherited Animalmethods and fields:

Dog dog = new Dog();
dog.name = "Fido";
dog.eat(); // 调用继承自Animal类的eat()方法
dog.bark(); // 调用Dog类的bark()方法

In this example, we are able to use dog.nameaccess to fields inherited from a Animalclass nameand use to call methods dog.eat()inherited from a Animalclass . eat()At the same time, we can also use the new method of dog.bark()the calling class .Dogbark()

It should be noted that inheritance in Java is single inheritance, and a subclass can only inherit one parent class. However, Java supports multi-level inheritance, that is, a class can directly inherit another class, and the latter can inherit other classes to form an inheritance hierarchy.

In addition, Java also provides interfaces ( interface) to implement interface inheritance, allowing classes to inherit a set of abstract methods by implementing interfaces. Unlike class inheritance, a class can implement multiple interfaces for greater flexibility and reusability.

To summarize, Java inheritance is a key concept of object-oriented programming, which allows subclasses to inherit properties and behaviors from parent classes. Through inheritance, we can reuse existing code and extend functionality. Use keywords extendsto declare that a subclass inherits from a parent class, and access the inherited fields and methods by instantiating the subclass.

In Java, the syntax for implementing inheritance is as follows:

class 父类 {
    
    
    // 父类的属性和方法
}

class 子类 extends 父类 {
    
    
    // 子类的属性和方法
}

in:

  • 父类Is a class that already exists, known as the base class or super class.
  • 子类is the new class to be created, known as a derived class or subclass.
  • extendsKeywords are used to indicate that a subclass inherits from a parent class.

Subclasses extendsinherit from a keyword followed by the name of the parent class. Inheritance means that the subclass inherits the non-private properties and methods of the parent class, and can add new properties and methods in the subclass, or override the methods of the parent class.

Java inheritance is an important concept of object-oriented programming, which allows a class (called subclass or derived class) to inherit the properties and methods of another class (called parent class or base class). Inheritance has the following benefits and characteristics in Java:

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

Java is a programming language that only supports single inheritance, which means that a class can only directly inherit from one parent class. This design is to avoid the complexity and potential conflicts caused by multiple inheritance.

However, Java supports multiple levels of inheritance, which means that a class can inherit from another class, which can in turn inherit from another class, forming an inheritance hierarchy. This inheritance relationship can continue forever, forming an inheritance chain.

For example, suppose we have class A and class B, class B inherits from class A, and then we have class C that inherits from class B. In this way, class C indirectly inherits the properties and methods of class A. This is a common form of inheritance in Java:

class A {
    // A's properties and methods
}

class B extends A {
    // B's properties and methods
}

class C extends B {
    // C's properties and methods
}

This multi-layer inheritance design makes code reuse more flexible, while maintaining the simplicity and ease of management brought by single inheritance.

Why can't java have multiple inheritance

1. Naming conflict: If there are methods or properties with the same name in two parent classes, the subclass will not know which parent class method or property to choose when inheriting. This conflict, known as the "diamond inheritance" (diamond inheritance) problem, can lead to confusing and difficult-to-maintain code.

What is Rhombus and Diamond Inheritance

: Diamond inheritance and diamond inheritance are two types of inheritance problems under the multiple inheritance model, and they can arise in some programming languages, especially languages ​​that support multiple inheritance. While Java does not support multiple inheritance, some other programming languages ​​such as C++ may face these issues.

  1. Diamond Inheritance:
    Diamond Inheritance occurs when a class inherits from two indirect common parent classes. In simple terms, if there is a class A, two classes B and C inherit directly from A, and then there is a class D inheriting from B and C, which forms a diamond inheritance structure. Because both B and C inherit from A, D will indirectly inherit the members of A, causing two copies of the members in A to exist in D, which may lead to duplicate definitions and redundancy.
   A
  / \
 B   C
  \ /
   D
  1. Diamond Inheritance:
    Diamond Inheritance is a special case of Diamond Inheritance which occurs when a class inherits from two immediate common parent classes. In simple terms, if there is a class A, two classes B and C are directly inherited from A, and then there is a class D that inherits from both B and C, this forms a diamond inheritance structure. Because B and C both inherit from A, and D inherits from both B and C, D will directly inherit from the members of A twice, which may cause ambiguity and conflicts in method calls.
   A
  / \
 B   C
  \ /
   D

In languages ​​that support multiple inheritance, if diamond inheritance and diamond inheritance are not handled properly, it can lead to confusion and errors in programming. Therefore, some languages ​​avoid these problems by adopting the concept of interface (Interface) instead of multiple inheritance. Interfaces only define method signatures, not implementations. A class can implement multiple interfaces, thereby achieving an effect similar to multiple inheritance, but avoiding conflicts and ambiguities.

2. Increased complexity: Multiple inheritance will increase the complexity of the code, because subclasses may inherit different behaviors from multiple parent classes, rather than simply inheriting the behavior of one parent class.

3. Breaking encapsulation: Multiple inheritance may break the encapsulation of a class, because a subclass can access the implementation details of multiple parent classes, which may lead to increased code coupling.

Although Java itself does not support multiple inheritance, it provides a mechanism similar to multiple inheritance through interfaces. A class can implement multiple interfaces to obtain methods defined in multiple interfaces, which can make up for the limitation of single inheritance to a certain extent. The interface method also avoids the diamond inheritance problem, because the interface only defines the signature of the method and does not contain the implementation.

// 定义接口
interface Interface1 {
    
    
    void method1();
}

interface Interface2 {
    
    
    void method2();
}

// 实现接口
class MyClass implements Interface1, Interface2 {
    
    
    @Override
    public void method1() {
    
    
        // 实现method1的具体逻辑
    }

    @Override
    public void method2() {
    
    
        // 实现method2的具体逻辑
    }
}

When talking about the benefits of inheritance, we usually mention the following aspects:

  1. Code reuse:
    Inheritance is an important concept in object-oriented programming, which allows subclasses to inherit the properties and methods already defined by the parent class. In this way, subclasses can directly use the functions of the parent class without writing the same code repeatedly. Through inheritance, subclasses can have all the functions of the parent class without destroying the original code, and can be extended and customized as needed. Code reuse greatly improves development efficiency, reduces code redundancy, and is also conducive to code maintenance and upgrades.

  2. Extensibility:
    Inheritance makes code more flexible and extensible. Subclasses can extend the functionality of the parent class by adding new properties and methods to meet specific needs. This extension is an incremental improvement based on the original code and will not affect the existing code. For example, suppose there is a general graphics class, subclasses can inherit it to create specific types of graphics such as circles, squares, triangles, etc., and can add specific properties and methods for each type of graphics without rewriting the general Graphics operation code.

  3. Uniformity:
    Inheritance can help improve code uniformity. When multiple classes have common attributes and methods, these common parts can be abstracted into a parent class, and the subclasses only need to focus on implementing their own specific functions. In this way, the code is clearer, more concise, easier to understand and maintain. Inheritance can realize the modularization of the code, making the code structure more reasonable and organized.

Although inheritance provides the benefits of code reuse, extensibility, and uniformity to a certain extent, it should also be noted that excessive use of inheritance can lead to complex inheritance hierarchies, making code understanding and debugging difficult. Therefore, in the design, you should weigh the use of inheritance scenarios to avoid abuse, but choose appropriate abstraction and design patterns to optimize the code structure.

Features:

  1. Single inheritance:
    Classes in Java only support single inheritance, that is, a subclass can only inherit from one parent class. This design is to avoid the complexity and conflicts that multiple inheritance may bring. If a class can inherit multiple parent classes at the same time, when there are methods or properties with the same name in these parent classes, the compiler cannot determine which one should be used, which may cause ambiguity. In order to maintain the clarity and simplicity of the code, Java has chosen to support only single inheritance model.

  2. Multi-Level Inheritance:
    Even though Java only supports single inheritance, it supports multi-level inheritance also known as hierarchical inheritance. This means that a class can inherit from another class, which in turn can inherit from another class, forming an inheritance hierarchy. Such an inheritance chain can be extended to achieve code reuse and expansion. An example of multi-level inheritance can be that class A inherits from class B, class B inherits from class C, and so on, forming an inheritance chain.

  A (subclass)
  |
  B (subclass, superclass)
  |
  C (superclass)
  1. Access control:
    After the subclass inherits the properties and methods of the parent class, it can determine its own access to these members according to the access modifiers of the parent class members. In Java, there are four access modifiers:
  • public: public access modifier, members declared as public can be accessed by any class.
  • protected: Protected access modifier, members declared protected can be accessed by subclasses, as well as other classes in the same package.
  • default (default): If no access modifier is explicitly specified, the member will have default access rights and can be accessed by other classes in the same package.
  • private: private access modifier, members declared as private can only be accessed by methods of this class, other classes cannot be directly accessed.

After inheritance, the subclass can access all non-private members inherited from the parent class (that is, members of public, protected, and default access rights), but cannot directly access the private members of the parent class. Subclasses can reuse and customize parent class members through inheritance and access control mechanisms.

Characteristics of inherited subclasses: subclasses can be used directly and new functions can be added

  1. The subclass inherits the non-private properties and methods of the parent class, and can use these properties and methods directly without reimplementation.

  2. Subclasses can change the behavior of methods inherited from parent classes by rewriting (overriding) methods. If the subclass defines a method with the same name and parameter list as the parent class, the subclass object will execute the method of the subclass instead of the method of the parent class when calling the method.

  3. Subclasses can have their own unique properties and methods to meet their specific needs.

  4. If the constructor of the subclass does not explicitly call the constructor of the parent class, by default, the Java compiler will automatically insert a call to the no-argument constructor of the parent class in the subclass constructor (provided that the parent class has a no-argument constructor method). If the parent class does not have a parameterless constructor, the subclass must explicitly call other constructors of the parent class in the constructor.

Excessive inheritance can lead to tight coupling between classes, reducing the maintainability and readability of the code. Therefore, in practice, other design patterns such as Composition should be given priority in order to better achieve code flexibility and maintainability.

[1] Each class inherits directly or indirectly from object:

In Java, every class inherits from directly or indirectly java.lang.Object, which is the basic design principle of Java language. Even if you don't explicitly specify a parent class when you define a class, Java will automatically inherit it from the Objectclass.

java.lang.ObjectIs the root class (Root Class) in the Java class inheritance hierarchy, which is at the topmost level of the class inheritance hierarchy. This means that all Java classes can call Objectmethods in the class because those methods are available in all classes.

ObjectThe class contains some commonly used methods, such as toString(), equals(), hashCode(), getClass()and so on. These methods are available to all Java objects, since all classes are Objectsubclasses of .

class MyClass {
    
    
    private int value;

    public MyClass(int value) {
    
    
        this.value = value;
    }

    // MyClass类继承自Object,即使没有显式声明
    // 以下的方法在所有的类中都可用
    @Override
    public String toString() {
    
    
        return "MyClass[value=" + value + "]";
    }
}

public class Main {
    
    
    public static void main(String[] args) {
    
    
        MyClass obj = new MyClass(42);

        // 使用Object类的toString方法
        System.out.println(obj.toString()); // 输出:MyClass[value=42]
    }
}

In the above example, we defined a MyClassclass called and created an object obj. Although we didn't explicitly declare MyClassthat inherits from Objectthe class, it automatically inherits from Objectthe class, so methods of the class can MyClassbe used in Object, eg toString().

Summary:
Every class in Java inherits directly or indirectly from classes java.lang.Object. This makes Objectthe methods of the class available to all Java objects, and also makes the inheritance hierarchy of the Java language consistent.

[2] Single inheritance: Classes in Java only support single inheritance, and a subclass can only inherit one parent class. This means that a class cannot inherit from more than one parent class at the same time.

There can be multiple branches, but there can only be one parent class

[3] Multi-layer inheritance: The inheritance hierarchy should be designed reasonably to avoid overly complicated inheritance relationships ----> subclass A inherits parent class B, and parent class B can inherit parent class C:

在 Java 中,类的继承可以分为两种类型:直接继承和间接继承。

When a class inherits another class in Java, it acquires the properties and methods of the inherited class. This way of inheritance is called subclass inherits from parent class. In Java, a class can have a direct parent class, but can indirectly inherit the characteristics of other classes through the inheritance chain, thus forming a more complex inheritance system.

1. Direct Inheritance:

Direct inheritance means that one class explicitly extendsinherits from another class through the keyword. When a class directly inherits from another class, it can access all non-private members (properties and methods) in the parent class, which can be, publicor protectedthe default (package-private) access modifier. Direct inheritance allows subclasses to reuse the code of the parent class, and can add new features or override methods of the parent class in the subclass.

class Animal {
    
    
    void makeSound() {
    
    
        System.out.println("动物发出声音");
    }
}

class Dog extends Animal {
    
    
    void bark() {
    
    
        System.out.println("狗在汪汪叫");
    }
}

In the above example, Dogthe class directly inherits from Animalthe class, which is Animala subclass of the class.

2. Indirect Inheritance:

Indirect inheritance means that a class indirectly inherits the properties and methods of other classes through the inheritance chain. Since Java only supports single inheritance, a class can only have one direct parent class, but can obtain characteristics from multiple classes through indirect inheritance. This inheritance system forms an inheritance hierarchy, where the top class is Objectthe class, which is the root class for all classes. ObjectAll classes are subclasses of class in the inheritance chain .

For example, consider the following class inheritance relationship:

Object
   |
   +-- Animal
         |
         +-- Mammal
               |
               +-- Dog
- `Animal` 类是 `Object` 类的子类。它可以直接访问 `Object` 类中的公共方法(如 `toString()`、`equals()` 等)。
- `Mammal` 类是 `Animal` 类的子类。因此,它不仅继承了 `Object` 类的方法,还继承了 `Animal` 类中的方法。
- `Dog` 类是 `Mammal` 类的子类。因此,它继承了 `Object`、`Animal` 和 `Mammal` 类中的方法。
- 通过这种继承层次结构,`Dog` 类间接地继承了 `Object` 类中定义的方法,而无需在 `Dog` 类中显式声明继承自 `Object`。

Sample code:

class Animal {
    
    
    void makeSound() {
    
    
        System.out.println("动物发出声音");
    }
}

class Mammal extends Animal {
    
    
    // Mammal类间接继承了Animal类的makeSound方法
}

class Dog extends Mammal {
    
    
    void bark() {
    
    
        System.out.println("狗在汪汪叫");
    }
}

In the example above, Mammalthe class indirectly inherits from Animalthe class, which Dogin turn inherits directly from the Mammalclass. Thus, Doga class indirectly inherits the methods Animalof the class through the inheritance chain makeSound().

Summarize:

  • Direct inheritance means that a class directly inherits from another class, using extendsthe keyword to achieve.
  • Indirect inheritance means that a class inherits the properties and methods of other classes through the inheritance chain, and is realized through multi-level inheritance.
  • Java supports single inheritance. A class can only have one direct parent class, but more features can be obtained through indirect inheritance.

other instructions

Advantages of inheritance:

  1. Code reuse: subclasses can inherit the properties and methods of the parent class, thereby avoiding repeated writing of the same code in subclasses and improving code reusability.
  2. Extensibility: subclasses can add new features or behaviors on the basis of inheriting the parent class, so that the program can be easily extended and modified.
  3. Hierarchy: Inheritance forms a hierarchy of classes, making code more organized and understandable.
    Java does not support multiple inheritance, but supports multi-level inheritance: Since Java only allows single inheritance, a class cannot inherit multiple direct parent classes at the same time. However, Java supports multi-level inheritance, that is, indirectly inheriting the characteristics of other classes through the inheritance chain. Subclasses can inherit the parent class of the parent class, thus forming a multi-layer inheritance system on the inheritance chain.

Precautions:

  1. Single inheritance: Java only supports single inheritance, that is, a class can only have one direct parent class. This is to avoid the complexity and conflicts that multiple inheritance can bring. A class can only inherit one direct parent class in Java, which is the single inheritance principle of Java language design. Therefore, each class can only have one direct parent class, which helps to keep the code concise and the inheritance relationship clear.
  2. Inheritance hierarchy: The inheritance hierarchy should be designed reasonably to avoid overly complicated inheritance relationships and keep the inheritance chain clear and concise.
  3. Access control: Subclasses can access publicthe and protectedmembers of the parent class, but not the members of the parent class private.
  4. All classes in Java are directly or indirectly inherited from the Object class : In Java, if a class does not explicitly specify a direct parent class, it will inherit from the java.lang.Object class by default. Therefore, all Java classes can directly or indirectly access the methods defined in the Object class (such as toString(), equals(), etc.) through the inheritance chain.

What subclasses inherit: class members (constructors, member variables, member methods)

In object-oriented programming, subclasses inherit the members of the parent class, including constructors, member variables (also known as attributes or fields), and member methods (also known as functions or methods). Inheritance is an important feature of object-oriented programming, which allows subclasses to inherit existing properties and behaviors from parent classes, making code more flexible, reusable, and easy to maintain.

Specifically, when a subclass inherits from a parent class, the subclass will get all non-private members defined in the parent class. Following are the three main members that subclasses can inherit during inheritance:

  1. Constructor:
    A constructor is a special method used to initialize an object. When an object is created, the constructor is called to initialize the object's state. The subclass inherits the constructor of the parent class, which means that the subclass can use the constructor of the parent class to create objects and perform initialization operations. Usually in the constructor of the subclass, the constructor of the parent class can be called to ensure that the initialization logic defined in the parent class can also be executed.

  2. Member Variables (Properties or Fields):
    Member variables are variables in a class that store data and they represent the state of an object. The subclass inherits the member variables of the parent class, which means that the subclass can directly access and use the member variables defined in the parent class without redeclaration.

  3. Member method (function or method):
    A member method is a function defined in a class to perform an operation. The subclass inherits the member methods of the parent class, which means that the subclass can directly call the methods defined in the parent class without redefinition. The subclass can also override (Override) the method of the parent class, that is, redefine a method with the same signature as the parent class method in the subclass, thereby changing or extending the behavior of the parent class method.

It should be noted that inheritance does not inherit the private members of the parent class (private members), private members can only be accessed inside the parent class, and subclasses cannot directly access them. But subclasses can indirectly access and manipulate private members through the public methods provided by the parent class.

Whether the constructor can be inherited

1. Constructor:

没有继承关系直接说明时,就自动加载object字节码文件
  • Private constructor: Subclasses cannot inherit the private constructors of the parent class, because private constructors can only be accessed inside the parent class, == subclasses cannot be directly called or inherited. == This means that subclasses cannot reuse the private constructors of the parent class through inheritance.
  • Non-private constructors: subclasses cannot inherit non-private constructors from parent classes. Although the subclass will call the no-argument constructor of the parent class by default (if no other constructor is explicitly called), the subclass does not really inherit the constructor definition of the parent class. The construction method of the subclass just calls the construction method of the parent class to initialize the member variables of the parent class during execution, and the subclass itself does not get the actual definition of these construction methods.

Why no matter how the construction method is modified, the subclass cannot inherit —> violates the class name = = construction method name = = file name, you need to rewrite it yourself

Constructors are special methods used to create objects in Java. They have the following characteristics:

  1. The name of the constructor must be exactly the same as the class name, including capitalization.
  2. Constructors have no return type, not even void.
  3. Constructors cannot be called directly, but are called automatically by the "new" keyword when an object is created.
  4. The constructor is used to initialize the state of the object, including setting the initial values ​​of member variables and performing other necessary initialization operations.

Since constructors are used to create objects and initialize them, their main purpose is to create new instances and ensure proper initialization of objects. Therefore, constructors are not inherited.

When we create a subclass, the compiler will automatically generate a default constructor for the subclass, which calls the no-argument constructor of the parent class (if any) to initialize parts of the parent class. In this way, the constructor of the parent class will be called indirectly when creating the subclass object, but it is not a real inheritance.

However, if the parent class defines a parameterized constructor and does not provide a no-argument constructor, the subclass must explicitly call the parent class's parameterized constructor to initialize parts of the parent class. At this time, we use the "super" keyword to call the constructor of the parent class in the constructor of the subclass.

Summary:
Constructors have no inheritance because they are special methods used for object initialization. The subclass will call the no-argument constructor of the parent class by default (if any), but this is not the inheritance of the constructor itself, but the indirect call of the parent class constructor when the subclass object is initialized. If initialization is required in a subclass, the superclass constructor must be called explicitly, usually by using the "super" keyword.

Code example:

public class Test {
    
    
    public static void main(String[] args) {
    
    
        ChildClass child1 = new ChildClass();
        ChildClass child2 = (ChildClass) new ParentClass("John Doe", 30);
        ParentClass parent3 = new ParentClass("Jane Smith", 25);
        ChildClass child4 = (ChildClass) new ChildClass("Alice Johnson", 28);
    }
}

class ParentClass {
    
    
    String name;
    int age;

    public ParentClass() {
    
    
    }

    public ParentClass(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }
}

class ChildClass extends ParentClass {
    
    

    public ChildClass(String name, int age) {
    
    
        super(name, age);
    }

    public ChildClass() {
    
    
        super();
    }
}
line by line explanation
For 1:
// 利用空参构造创建子类对象,Java 编译器会为子类生成一个默认的空参数构造方法。
ChildClass child1 = new ChildClass();

This paragraph illustrates the use of the default constructor (an empty constructor with no parameters) to create a subclass object (ChildClass). It mentions that if no constructor is explicitly defined, the Java compiler automatically generates a default constructor for subclasses to use.

For 2:
// 利用带参构造创建子类对象
// 使用父类的带参构造函数来创建子类对象child2,这是一个不推荐的写法,虽然合法但会导致对象类型和实际初始化方式不一致。
ChildClass child2 = (ChildClass) new ParentClass("John Doe", 30);

This section discusses the use of parameterized constructors to create subclass objects (ChildClass). It states that in this case the constructor of the parent class (the ParentClass constructor with parameters) is used to create the ChildClass object (child2). While this is a valid approach, it is not recommended because it results in an inconsistency between the type of the object (ChildClass) and how it is actually initialized (using the parent class's constructor).

For 3:
ParentClass parent3 = new ParentClass("Jane Smith", 25);
// 使用父类的带参构造函数来创建父类对象parent3。
// 创建一个 ParentClass 类的对象 parent3,通过调用带参数构造函数 ParentClass(String, int) 来完成初始化。

This paragraph describes the use of a parameterized constructor to create a parent class object (parent3). It simply explains ParentClass(String, int)creating a ParentClass object by using the constructor and passing in the parameters "Jane Smith" and 25.

For 4:
ChildClass child4 = (ChildClass) new ChildClass("Alice Johnson", 28);
// 使用子类的带参构造函数来创建子类对象child4,这是推荐的方式。
// 创建一个 ChildClass 类的对象 child4,通过调用子类的带参数构造函数 ChildClass(String, int) 来完成初始化。
// 直接使用子类构造函数来创建子类对象是符合面向对象设计原则的。

This paragraph explains the recommended way to create a subclass object ( child4 ) using the subclass's constructor with parameters. Emphasize that using subclass constructors directly to create subclass objects conforms to object-oriented design principles. The constructor ChildClass(String, int)is used to initialize the object, and the parameters "Alice Johnson" and 28 are passed in.

For 5:
class ParentClass {
    
    
    String name;
    int age;

    // 父类的空参构造函数
    public ParentClass() {
    
    
    }

    // 父类的带参构造函数
    public ParentClass(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }
}

class ChildClass extends ParentClass {
    
    

    // 子类的带参构造函数
    public ChildClass(String name, int age) {
    
    
        // 这里可以添加子类特有的初始化逻辑
        super(name, age); // 调用父类的带参构造函数来完成初始化
    }

    // 子类的空参构造函数
    public ChildClass() {
    
    
        // 这里可以添加子类特有的初始化逻辑
        super(); // 调用父类的空参构造函数来完成初始化
    }

    // 可以在这里添加子类的其他代码。
}

2. Member variables: all can be inherited, but must be obtained through get and set methods

  • Private member variables:Subclasses cannot directly inherit the private member variables of the parent class, because private member variables can only be accessed inside the parent class. Subclasses can only indirectly access these private member variables through the public/protected methods provided by the parent class, or redeclare member variables with the same name in the subclass to achieve similar functions.
  • Non-private member variables: Subclasses can inherit non-private member variables of the parent class, which means that the subclass will have member variables of the same name and type as the parent class. Subclasses can directly access inherited member variables and modify or rewrite them as needed.

[1] Inheritance of non-private variables: The martialArt inherited by oneself has nothing to do with the parent class. This is a new class

package work0729;

public class TTest {
    
    
    public static void main(String[] args) {
    
    
        Child c = new Child();
        c.favouriteGame = "堡垒之夜"; // 将变量名更改为 'favouriteGame',其值改为 "堡垒之夜"
        System.out.println(c);

        c.martialArt = "功夫熊猫"; // 将变量名更改为 'martialArt',其值改为 "功夫熊猫"
        System.out.println(c.favouriteGame + " " + c.martialArt);
    }
}

class Child extends People {
    
    
    String favouriteGame; // 将变量名更改为 'favouriteGame'
}

class People {
    
    
    String martialArt; // 将变量名更改为 'martialArt'
}
Even though the variable Childis not explicitly defined in the class martialArt, it can still access martialArtthe variable because it inherits Peopleall instance variables and members (non-private) of the parent class.

In Java, if a subclass does not explicitly define a constructor, it will implicitly inherit the no-argument constructor (default constructor) of the parent class, provided that the parent class has a no-argument constructor for inheritance. In this case, the parent class peoplehas a no-argument constructor, so the subclass Childinherits this no-argument constructor.

There are two constructors in the subclass Child: one is a parameterless constructor (the default constructor), and the other is a parameterized constructor. In a parameterized constructor, you can set favouritethe values ​​of the subclass's own instance variables. In the default constructor, the subclass will implicitly call the no-argument constructor of the parent class.

Within TTestthe class, you can create Childan object of the class and call its constructor without explicitly providing martialArta value for the variable. This is because Childthe class inherits peoplethe no-argument constructor of the class, which can initialize martialArtthe variable, so when Childthe object is created, martialArtthe variable is given a default value (such as null, for a variable of object type).

package work0729;

public class TTest {
    
    
    public static void main(String[] args) {
    
    
        Child c1 = new Child(); // 使用无参构造函数
        c1.favouritegame = "堡垒之夜";
        System.out.println(c1.favourite + " " + c1.martialArt); // martialArt 变量会有默认值

        Child c2 = new Child("英雄联盟"); // 使用带参数的构造函数
        System.out.println(c2.favouritegame + " " + c2.martialArt); // martialArt 变量会有默认值
    }
}

class Child extends People {
    
    
    String favouritegame;

    public Child() {
    
    
        // 隐式调用父类 People 的无参构造函数
    }

    public Child(String favouritegame) {
    
    
        this.favouritegame = favouritegame;
    }
}

class People {
    
    
    String martialArt;
}

Note that even though the variable Childis not explicitly defined in the class martialArt, it still has access to martialArtthe variable because it inherits Peopleall instance variables and members (non-private) of the parent class .

[2] Private how to access indirectly: the following get and set methods and the use of extended getset

package work0729;

public class People {
    
    
    private String martialArt;

    public People() {
    
    
    }

    public People(String martialArt) {
    
    
        this.martialArt = martialArt;
    }

    public String getMartialArt() {
    
    
        return this.martialArt;
    }

    public void setMartialArt(String martialArt) {
    
    
        this.martialArt = martialArt;
    }
}

public class Child extends People {
    
    
    String favoriteGame;
    String specialSkill = getMartialArt();

    public Child() {
    
    
    }

    public Child(String favoriteGame, String specialSkill) {
    
    
        this.favoriteGame = favoriteGame;
        this.specialSkill = specialSkill;
    }

    public String getFavoriteGame() {
    
    
        return this.favoriteGame;
    }

    public void setFavoriteGame(String favoriteGame) {
    
    
        this.favoriteGame = favoriteGame;
    }

    public String getSpecialSkill() {
    
    
        return this.specialSkill;
    }

    public void setSpecialSkill(String specialSkill) {
    
    
        this.specialSkill = specialSkill;
    }
}

public class TTest {
    
    
    public static void main(String[] args) {
    
    
        Child child = new Child("Chess", "Kung Fu");

        child.setMartialArt("Tai Chi");
        System.out.println(child.favoriteGame + " " + child.getMartialArt());
    }
}

In this code, the get and set methods in object-oriented programming in Java are involved, and the use of get and set methods is extended.

  1. getMethod:
    getA method is used to get the value of a member variable in a class. Here, getmartialArt()it is peoplea get method in the class, which is used to get martialArtthe value of the member variable.

  2. setMethod:
    setA method is used to set the value of a member variable in a class. Here, setmartialArt(String martialArt)it is peoplea set method in the class, which is used to set martialArtthe value of the member variable.

  3. Extend the use of get and set methods:
    In Childa class, in addition to inheriting the methods peopleof the class getmartialArt(), it also defines its own getGame()and getSs()method and setGame(String game)and setSs(String ss)method. These methods are used to get and set the value of favoriteGameand ssmember variables respectively.

In the method TTestof the class main, create Childan instance of the class cand pass in favoriteGamethe ssvalue of the sum, then call the value c.setmartialArt("fsdfdsf")set by the method martialArt, and obtain the value of the sum and output it to the console through c.favoriteGame()and c.getmartialArt()respectively .favoriteGamemartialArt

Please pay attention to a problem in the code:
in Childthe constructor of the class, there is already a pair ssof initialization statements , and then the value is set String ss = getmartialArt();by another constructor , which will cause the initialization of the constructor to be overwritten. You should choose to use one method to initialize , such as setting uniformly in the constructor, instead of mixing them.public Child(String favoriteGame, String ss)ssss

3. Member method:

  • Private member methods: == The subclass cannot directly inherit the private member methods of the parent class, because the private member methods can only be called inside the parent class. == Subclasses can only indirectly call these private member methods through the public/protected methods provided by the parent class, or define methods with the same name and parameter list in the subclass to achieve similar functions.
  • Non-private member methods: Subclasses can inherit non-private member methods of the parent class, including public, protected, and default access methods. Subclasses can call these methods directly, and override these methods in subclasses to change their behavior.

What is Java's virtual method table: When a class inherits from another class, it can override (override) the method of the parent class

Java's Virtual Method Table (Virtual Method Table, referred to as VMT) is a mechanism for implementing dynamic dispatch (Dynamic Dispatch). It is a data structure used to store the actual address of the virtual method in the class and its inheritance hierarchy. . . It is the basis for Polymorphism in Java.

In Java, == When a class inherits from another class, it can override (override) the method of the parent class. ==When calling this method through a reference of the parent class, it will actually decide which method to call based on the actual type of the object. This mechanism of determining method calls based on the actual type of the object is called dynamic dispatch.

当使用父类的引用调用方法时,根据引用的实际类型找到对应的虚方法表,
然后根据方法的索引或名称来查找要调用的方法的实际地址,从而实现多态性。

The virtual method table is a data structure introduced to realize dynamic dispatch. Every Java class has a virtual method table, which records all the virtual methods in the class and its inheritance hierarchy. The virtual method table is an array, and each element in the array is a function pointer, pointing to the actual implementation of the corresponding method.

与虚方法表对应的是实例对象的方法区(Method Area),其中保存了类的结构信息,包括方法代码等。
当创建对象实例时,对象并不包含自己的方法表。
	相反,对象存储了一个指向类的虚方法表的指针,以便可以在运行时通过该指针查找正确的方法地址。

When a method is called by a reference, the Java Virtual Machine (JVM) will find the corresponding virtual method table according to the actual type of the reference, and then find the actual address of the method to be called according to the index or name of the method. In this way, the method to be called can be dynamically determined at runtime, and polymorphism is realized.

It should be noted that the virtual method table is only related to the type of the class, and has nothing to do with the instance of the specific object. Each class has only one corresponding virtual method table, and there can be multiple instances of the class, and they share the same virtual method table.

The virtual method table is one of the important mechanisms for realizing polymorphism in Java. It enables the method call to be dynamically determined according to the actual type of the object at runtime, thereby increasing the flexibility and scalability of the program.

Summarize:

  1. Subclasses cannot inherit the private constructors, private member variables and private member methods of the parent class.
  2. Subclasses can inherit non-private constructors, non-private member variables, and non-private member methods of the parent class.
  3. For private constructors, member variables, and member methods, subclasses cannot directly access them, but they can indirectly access and use these private members through public/protected methods provided by the parent class.

The inheritance mechanism is an important feature of object-oriented programming, which allows subclasses to reuse the functions of the parent class and extend its behavior, which improves the reusability and maintainability of the code. At the same time, subclasses can also achieve polymorphism through method rewriting, which further enhances the flexibility and scalability of object-oriented programming.

Guess you like

Origin blog.csdn.net/m0_74154295/article/details/131820132