Classes have two important members: member variables and methods. Some of the members of a subclass are declared and defined by the subclass itself, while others are inherited from its parent class. The subclass inherits the member variable of the parent class as one of its own member variables, as if the member variable was directly declared in the subclass, and can be operated by any instance method defined in the subclass. The subclass inherits the method of the parent class as one of its own methods, as if the method was directly defined in the subclass, and can be called by any instance method defined in the subclass.
Inheritance between subclasses and parent classes in the same package:
If the subclass and the parent class are in the same package, then the subclass naturally inherits the non-private member variables in the parent class as its own member variables, and also naturally inherits the non-private methods in the parent class as its own. Access to methods, inherited member variables, or methods remains unchanged.
Inheritance when the subclass and parent class are not in the same package:
If the subclass and the parent class are not in the same package, the private and friendly access member variables in the parent class will not be inherited by the subclass, that is, the subclass only inherits the protected and public access member variables and methods in the parent class as Member variables and methods of subclasses.
Further explanation about protected:
The protected member variables and methods in a class A can be inherited by its descendant classes. For example, if B is a subclass of A, C is a subclass of B, and D is a subclass of C, then classes B, C, and D all inherit Protected member variables and methods of class A.
If you create an object in D itself using D class, then the object can always access inherited or self-defined protected variables and protected methods through the "." operator. However, if it is in another class, such as Other An object object is created using class D in the class. The permissions of this object to access protected variables and protected methods through the "." operator are as follows:
1. For the protected member variables and methods declared by subclass D itself, as long as the Other class and D class are in the same package, the object object can access these protected member variables and methods.
2. For the protected member variables or protected methods that subclass D inherits from the parent class, it needs to be traced back to the "ancestor" class where these protected member variables or methods are located. For example, it may be class A, as long as the Other class and class A are in the same package. , the object object can access inherited protected variables and protected methods.