About who calls the get method in inheritance

parent
public class Person {

  private String name;
  public Person(String name){
       this.name=name;
  }
  public void setName(String name){
      this.name=name;
  }
  public String getName(){
     return this.name;
 }

}
subclass
public class Student extends Person {

  public Student(String name){
       super(name);
 }
 public String print(){
       return getName();
 }
Who in the

}
subclass is calling the getName () method, and is it the subclass object that is calling it? This can be understood as this.getName () no, and the this here represents the current object (that is, the subclass object) that calls the method. The getName () method here inherits the method of the parent class, so which object is represented by the this, in this.name in this method? Please.

Oct.10,2021

return getName () means that return this.getName (), this is the current object that calls the method, and here you are the subclass Student object. The getName () method in
Student inherits from the parent class, so the this in this.name is, of course, a Student object. Remember, this points to the current object that calls the method.


java Polymorphism is achieved through invokevirtual instruction, and its calling process can be divided into the following steps:

  1. first find the actual type of object class; from the action stack
  2. find the method in class with the same signature as the called method. If you have access, return a direct reference to this method. If you do not have access, you will report an error
    java.lang.IllegalAccessError;
  3. .
  4. if no matching method can be found in step 2, search for the parent class of class and perform the operation in step 2 according to the inheritance relationship from bottom to top.
  5. if no matching method is found in step 3, an error java.lang.AbstractMethodError is reported;

it's obvious that you don't inherit the parent class's method here, so call the parent's getName method here. Of course, the parent class name attribute is also returned.

if your subclass inherits the getName method and returns return super.getName (); , then your print method calls the subclass's getName method, and then calls the parent's getName method (which, of course, returns the name property of the parent class).

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e5df47-44ac4.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e5df47-44ac4.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?