When the subclass of Java and the parent class have properties of the same name, what exactly does Java do with it?
Look at the code first:
Package Com.joyfulmath.study.field; Public class Person { public String name; Public String GetName () { return name; } }
package Com.joyfulmath.study.field; public class Student extends person { public String name; public Student (String name) { Span style= "color: #0000ff;" >this . Name = name; super . Name = "Man-person" ;//from here can be seen, Java can pass this, already super to the zone molecule class and the parent class. } @Override public String GetName () { return name; } }
Packagecom.joyfulmath.study.factory;ImportCom.joyfulmath.study.field.Person;Importcom.joyfulmath.study.field.Student;ImportCom.joyfulmath.study.utils.TraceLog; Public classFieldmethodImplementsIworkmethod {@Override Public voidstartwork () {Student St=NewStudent ("Mark-student"); Person P=St; TRACELOG.V (P.name+" "+st.name); TRACELOG.V (P.getname ()+" "+st.getname ()); }}
In fact, St.name no doubt, it must be mark-student.
But P.name, already p.getname ()?
Let's take a look at P.getname (), although P is person, but it actually represents the address that is stored in student, so
P.getname () the actual invocation result is the same as St.getname (), which is student's GetName method.
What about the p.name?
We add an attribute to the student, level.
public class Student "extends person { public String name; public int level; public Student (String name) { Span style= "color: #0000ff;" >this . Name = name; super . Name = "Man-person" ; } @Override public String GetName () { return name; } }
Then still in the Startwork, with the p.level, the result compiler does not know?
Yes, p is the object of person, how can it know?
So obviously, p only knows the name in the person, not the name in the student.
Let's look at the results of the operation:
Startwork:man-person mark-student [at (fieldmethod.java:13)]startwork:mark-student mark-student [at ( FIELDMETHOD.JAVA:14)]
Validates our guess that the visible attribute is of the binding type, and the method is bound to the object.
Or a property is confirmed in the compiler, and the method is dynamically bound (polymorphic).
Subclass Parent Class Property overrides for Java Foundation