The difference between this and super in java

    In Java, this usually refers to the current object, and super refers to the parent class. When you want to refer to something in the current object, such as a method of the current object, or a member of the current object, you can use this to achieve this purpose. Of course, another use of this is to call the current object. Another constructor, these will be discussed shortly. 
    this can only be used in non-static methods in a class. This must not appear in static methods and static code blocks. The  
    super key is similar to this. It is a masked member variable or member method or becomes visible, or is used to References to masked member variables and member methods. However, super is used in subclasses, the purpose is to access the masked members in the direct parent class, pay attention to the direct parent class (that is, the closest superclass above the class).  
    If you want to refer to something in the parent class, then super is the way to go. Since this and super have such similar properties and some innate relationship, we discuss them here, hoping to help you distinguish and master the two.   
The most common situation in general methods   
    is that a parameter name in your method has the same name as a member of the current object. In this case, in order to avoid confusion, you need to explicitly use the this keyword to indicate You want to use a member, the use method is "this.membername", and the one without this is the formal parameter.   
    In addition, you can also use "this. method name" to refer to a method of the current object, but this is not necessary at this time. You can directly use the method name to access that method, and the compiler will know that you want to call it. that one. The following code demonstrates the above usage:   

public class Chinese extends Person {  Chinese() { 

  super(); // call the parent class parameterless constructor (1) 

  prt("A chinese.");// (4) 
 } 
 
Chinese(String name) { 
 
super(name);// Call the constructor of the parent class with the same parameters (2
  prt("his name is:" + name); 
 } 

 Chinese(String name, int age) { 

  this(name);// Call the current constructor with the same parameters (3) 

  prt("his age is:" + age); 
 } 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324528472&siteId=291194637