The member variables of the parent class can be obtained through inheritance. member variables of the subclass include member variables inherited from the parent class (including member variables inherited from the ancestor class) and member variables redefined in the subclass. This introduction includes: What members can be inherited? What if the same member variables appear in the subclass and parent classes?
1. member variables that can be inherited
The inherited member variables are related to the access control type of member variables. The access control types of member variables include public, protected, default, and private.
After the subclass inherits the parent class, it can inherit the public and protected member variables of the parent class. For example:
Public Class Parent {
Public int I _public;
Int I _default;
Protected int I _protected;
Private int I _private;
}
Public class Child extends parent {
Private int I _child;
}
The member variables of the parent class include:
Public int I _public;
Int I _default;
Protected int I _protected;
Private int I _private;
The member variables of the subclass include:
Public int I _public; // inherits from the parent class
Protected int I _protected; // inherits from the parent class
Private int I _child; //
2. Override the member variables of the parent class
Assume that the parent class defines member variable A and can inherit from the quilt class, and the Child class defines member variable A. In this way, the Child class has two member variables named A. How can this problem be accessed?
Let's take a look at the following example:
Public Class Parent {
Public int A = 10;
}
Public class Child extends parent {
Public int A = 20;
}
Pubilc class test {
Public static void main (string ARGs []) {
Child child = new child ();
System. Out. println (child. );
}
}
What is the running result?
The result should be 20, that is, the value of the variable defined in the subclass.
How can I access the member variables defined in the parent class? First, convert the child type to the parent type and then access it.
System. Out. println (parent) Child). );
If the child class accesses its members and its parent class members through Super, for example, the following code:
Public int getparenta (){
Return super.;
}
Public int getchilda (){
Return;
}
You can use this to access member variables of subclass, for example, the following code:
Public int getchilda (){
Return this.;
}
Note:
1) The access controllers of the member variables inherited from the parent class are still the same.
2) The subclass defines the member variables with the same name as the parent class, and does not overwrite the member variables of the parent class. Instead, the two member variables coexist.
Last time: 35th lecture on Access Permissions next time: 37th lecture on inheritance and coverage of member Methods Li xucheng csdn blog: workshop? U= 124362 & C = 7be8ba2b6f3b6cc5