Class first:
package ExtendsTest;public class First { int a=1; public void print() { System.out.println(a); }}
The second type is as follows:
package ExtendsTest;public class Second extends First{ int a=2; int b=3; public void print() { System.out.println(a); }}
Run the following code:
package ExtendsTest;public class Test { public static void main(String []args) { First c1=new Second(); System.out.println(c1.a); c1.print(); Second c2=new Second(); System.out.println(c2.a); c2.print(); }}
The output result is 1 2 2 2.
Focus on system. Out. println (c1.a );
C1.print ();
Why are the output results 1 and 2.
Because in the Inheritance Mechanism of Java, if the object of the subclass is accessed by reference of the parent class.
For the member variables redefined by the quilt class, the parent class accesses its own member variables.
That is to say, the member variables are accessed Based on the referenced type.
The methods are different. If the parent class references a method that calls a quilt class override, the method accessed is the sub-class.
Class method.
This seems to be called dynamic binding.
That is to say, the member method is accessed Based on the object type.
Summary:
Methods and variables for quilt class rewriting. The preceding a variable and print () method.
When accessing with the parent class reference (first C1) pointing to the subclass object (new second.
Its member variables. The parent class accesses the member variables of the parent class.
Its member method. The parent class accesses the member method of the subclass.