Now on a face test
public class MainClass {
public static void Main (string[] args) {
Fu f = new Zi ();
Zi z = new Zi ();
System.out.println ("F.num:" +f.num);
System.out.println ("Z.num:" +z.num);
System.out.println ("F.num:" +f.num2);
System.out.println ("Z.num:" +z.num2);
F.method1 ();
Z.method1 ();
F.METHOD4 ();
Z.METHOD4 ();
}
}
Abstract class fu{
public int num = 5;
public int num2 = 7;
Public Fu () {
num2 = 9;
Method3 ();
}
public void Method1 () {
System.out.println ("Fu method1");
}
void Method3 () {
System.out.println ("Fu method3");
}
static void Method4 () {
System.out.println ("Fu method4");
}
}
Class Zi extends fu{
public int num = 6;
public int num2 = 8;
public void Method1 () {
System.out.println ("Zi method1");
}
void Method3 () {
System.out.println ("Zi method3");
}
static void Method4 () {
System.out.println ("Zi method4");
}
}
This problem, if not a deep understanding of Java inheritance processing, still difficult to answer.
In fact, to master a principle, it is original aim: for member method is overwrite, for member variable and static method is hidden
How do you understand this sentence?
1. If the subclass overrides the member method of the parent class, then it is overwrite, that is, after new Zi (), there is only one method of the subclass in the new instance, whether the type you are declaring is a parent class or a subclass.
2. If the subclass has a member variable of the same name as the parent class, then it is hidden, so the so-called Hide is New Zi (), there will be two member variables in the instance, whichever is determined by the type of claim.
3. If the subclass overrides the static method of the parent class, it is also hidden, and the invocation is determined by the claim type.
Now we analyze the above interview questions:
Fu f = new Zi (); This is certainly the most confusing of us, but according to our principles above is very good processing, know f.num=5, that is, the member variable is determined by the declaration type, the equivalent of hiding the NUM variable in the subclass;
F.METHOD1 () calls the implementation of subclasses, that is, full coverage, which is equivalent to only subclasses of a method in the instance; f.method4 (); Similar to member variable handling, which is equivalent to hiding the implementation in subclasses;
Final output Result:
Zi method3
Zi method3
F.num:5
Z.num:6
F.num:9
Z.num:8
Zi method1
Zi method1
Fu METHOD4
Zi METHOD4
Everyone should understand.
Three-minute understanding of Java inheritance and polymorphism principles