When working with member variables in a Java class, it is not a run-time binding, but a static binding in the general sense. So in the case of an upward transformation, the object's method can find the subclass, and the object's properties are also the properties of the parent class.
The code is as follows:
Java code
public class Father {
Protected String name= "Father attribute";
public void Method () {
System.out.println ("Parent class method, Object type:" + this.getclass ());
}
}
public class Son extends Father {
Protected String name= "son attribute";
public void Method () {
System.out.println ("Subclass method, Object type:" + this.getclass ());
}
public static void Main (string[] args) {
Father sample = new Son ();//Upward transformation
System.out.println ("called Member:" +sample.name);
}
}
conclusion, the calling member is the parent attribute.
Now trying to call the member variable name of the subclass, what do I do? The simplest approach is to encapsulate the member variable into a method getter form.
The code is as follows:
Java code
public class Father {
protected String name = "Father Attribute";
Public String GetName () {
return name;
}
public void Method () {
System.out.println ("Parent class method, Object type:" + this.getclass ());
}
}
public class Son extends Father {
Protected String name= "son attribute";
Public String GetName () {
return name;
}
public void Method () {
System.out.println ("Subclass method, Object type:" + this.getclass ());
}
public static void Main (string[] args) {
Father sample = new Son ();//Upward transformation
System.out.println ("called Member:" +sample.getname ());
}
}
Result: The property of the son is called
Sample is of type father, sample can see the property name of Father Class name, method name GetName and method name, when the GetName method is called, sample first find its own method name GetName, Then take the method name GetName to the code area to find the method body, found that there are two getname methods, virtual machine to see the specific object is son, chose son's GetName method
Why do you have a Get method? -Application of polymorphic memory analysis