I saw a question about java inheritance on the Internet. I think this is a problem that many beginners should pay attention.
Public abstract class {
Int I = 1;
Public void printI (){
System. out. println ("I =" + I );
}
}
Public class B extneds {
Int I = 2;
Public static void main (String [] args ){
B B = new B ();
B. printI ();
}
}
So what is the I value of the console?
If you can get the correct result 1 after a while, you do not need to read the following part.
1. class inheritance knowledge points
(1) java does not support multi-inheritance. That is to say, a subclass can have at most one parent class.
(2) subclass inherits the non-private member variables and member methods in its parent class as its member variables and methods.
(3) If the member variables defined in the subclass are the same as those defined in the parent class, the member variables in the parent class cannot be inherited.
(4) The member method defined in the subclass. The member method name, return type, number of parameters, and type are exactly the same as a member method of the parent class, the member methods of the parent class cannot be inherited.
2. The answer is two.
If the name of variable I in subclass B is the same as that in parent class A, the variable I in subclass B will overwrite the variable I with the same name in parent class. when accessing the variables in the parent class, jvm will cast the subclass to the parent class. therefore, the printed result should be "I = 2 ";
3. Ambiguity
The key to ambiguity generation is that variable I in subclass B overwrites the same name variable I in the parent class. Here, I think these two words are easy to mislead. It should be shielded or hidden. In this case, the member variables of the parent class are not changed.
4. jvm Execution Process
(1) The constructor of subclass B is called to instantiate an object B. The members of object B are initialized.
(2) jvm implicitly calls the constructor of the parent class, instantiates an object A, and the members of object A are initialized.
(3) The printI () function of object A is called because the printI () function of object A is not blocked.
In this case, the member function of A accesses its member variable.
5. super keyword
The role of the super keyword in java is to make the blocked member variables or member Methods visible, or to reference the blocked member variables and Member member methods. Super is used in subclass to access the blocked members in the direct parent class. The above code can also be written as follows:
Public abstract class {
Int I = 1;
Public void printI (){
System. out. println ("I =" + I );
}
}
Public class B extends {
Public int I = 2;
Public void printI (){
Super. printI ();
}
Public static void main (String [] args ){
B B = new B ();
B. printI ();
}
}