Take a look at the code below, and if you can get the right answer without running, you're really over 99% Java programmers. [I belong to the largest part of the head]
public class a{Public String s = "A"; public void Sets (String s) { THIS.S = s; } Public String GetS () { return this.s; } } public Class B extends a{public String s = "B"; public void Sets (String s) { THIS.S = s; } Public String GetS () { return this.s; } public static void Main (string[] args) { A A = new A (); b b = new B (); A.sets ("[AA]"); B.sets ("[BB]"); A = b; System.out.print (A.S); System.out.print (B.S); System.out.print (A.gets ()); System.out.print (B.gets ()); } }
What is the result of the output? [AA] [BB] [AA] [BB] or [AA][BB][BB][BB], which of these two answers would you choose? Actually these two answers are all wrong, correct is: A[BB][AA][BB]. One of the knowledge points examined here is that the reference to the subclass refers to the parent class type to see if you understand it in depth.
In Java inheritance, the attribute is not polymorphic, only the method supports polymorphism. You might think that the method does not support polymorphism then A.S will output "[AA]". Actually when executed a = B; After this assignment, the A object has nothing to do with his original new object.
Before the B object is constructed, the JVM initializes and generates an instance of the parent class of the B object, which is the class A object, and the property s of the A object is, of course, initialized to "a" by default. Executes A = b This statement, a object is actually a hidden parent object that points to the B object ( Is the parent object that was constructed before the B object was generated), we can understand why we are outputting this result. Then the result of the method call output, naturally embodies the polymorphism of Java in the following three results are "[BB]."
[Due to the limited capacity of individuals, write inaccurate places welcome everyone to correct, learn together!]
Reference: http://blog.csdn.net/zdwzzu2006/article/details/5979886
Test your understanding of Java polymorphism