The tests are summarized as follows:
Member variables in inheritance:
First run the Code:
Public class Testextends {
Int a = 0;
Public static void main (String [] args ){
Sub s = new Sub ();
System. out. println (s. );
System. out. println (Testextends) s). );
}
}
Class Sub extends Testextends {
Int a = 1;
}
Print result:
1
0
Cause: because a is defined in the parent class, a in Sub is not the same variable as a in Testextends.
So when printing s. a, it will print 1. After the conversion, it prints a in the parent class, that is, 0.
Traditionally, subclass inherits the parent class and shares a with the parent class. The premise is that the subclass does not define variables with the same name as the parent class. Demo:
Class Sub extends Testextends {
// Public final static String foo = "ball ";
Public Sub (){
A = 1;
}
}
The output is.
Excerpted from: wandering Xiao Qi's column