Java keywords (2): this and super



foreword

This blogger will use CSDN to record the experience and knowledge gained and learned on the road of software development and learning. Interested friends can follow the blogger!
Maybe a person walking alone can go very fast, but a group of people walking together can go further! Let us learn from each other on the road of growth, welcome to pay attention!

1. Use of "this" keyword

1 Overview

  • what is this?

In Java, the thiskeyword is more difficult to understand, its role is very close to its meaning, which means "current".

2. Function

⭕Keywords thiscan be used to modify and call: properties, methods, constructors.
⭕Keywords thiscan only be used inside methods.
⭕ It is used inside a method, that is, a reference to the object to which this method belongs;
⭕ It is used inside a constructor, indicating the object that the constructor is initializing.

3. Use

  • When to use the this keyword?

It is used when the object that calls the method needs to be used within the method this. Concrete: We can thisuse to distinguish between properties and local variables. for example:this.name = name;

3.1 Modified properties and methods

thisis understood as: the current object or the object currently being created
⭕ In the method of the class, we can use the this.属性or this.方法method to call the properties or methods of the current object. Often, however, we choose to omit this.. In special cases, if the formal parameter of the method and the property of the class have the same name, we must explicitly use this.变量the method to indicate that this variable is a property, not a formal parameter.
⭕ When using thisaccess properties and methods, if it is not found in this class, it will be looked up from the parent class.

Code demo:

class Person{
     
      // 定义Person类
    private String name ;
    private int age ;
    public Person(String name,int age){
     
     
      this.name = name ; 
      this.age = age ; }
    public void getInfo(){
     
     
      System.out.println("姓名:" + name) ;
      this.speak();
    }
    public void speak(){
     
     
      System.out.println(“年龄:” + this.age);
    } 
}

3.2 Calling the constructor

⭕ In the constructor of the class, we can use the this.属性or this.方法method to call the properties or methods of the object currently being created. Often, however, we choose to omit this.. In special cases, if the parameter of the constructor and the property of the class have the same name, we must explicitly use this.变量the method to indicate that this variable is a property, not a parameter.

⭕ In the constructor of a class, we can call other constructors specified in this class in an explicit this(形参列表)way.

⭕ A constructor cannot this(形参列表)call its own constructor by means.

⭕ If there are n constructors in a class, at most n - 1 constructors are usedthis(形参列表)

⭕ Requirements: It this(形参列表)must be declared in the first line of the current constructor .

⭕ Inside a constructor, at most one can be declared this(形参列表)to call other constructors.

⭕ The compiler prohibits calling the constructor from any method other than the constructor.

Code demo:

class Person{
     
      // 定义Person类
   private String name ;
   private int age ;
   public Person(){
     
      // 无参构造器
     System.out.println("新对象实例化") ;
   }
   public Person(String name){
     
     
     this(); // 调用本类中的无参构造器
     this.name = name ;
   }
   public Person(String name,int age){
     
     
     this(name) ; // 调用有一个参数的构造器
     this.age = age;
   }
   public String getInfo(){
     
     
     return "姓名:" + name + ",年龄:" + age ;
   } 
}

3.3 Return the current object

Code demo:

public class Leaf {
     
     
    int i = 0;
    Leaf increment(){
     
     
        i++;
        return this;
    }
    void print(){
     
     
        System.out.println("i = "+i);
    }
    public static void main(String args[]){
     
     
        Leaf x = new Leaf();
        x.increment().increment().increment().print();//i = 3
    }
}

Second, the use of "super" keyword

1 Overview

(1) superIt is understood as: the parent class

(2) Use super in the Java class to call the specified operation in the parent class:
superCan be used to access the properties defined in the parent class .
⭕ can be used to call member methodssuper defined in the parent class . Can be used to call the superclass's constructor in the subclass's constructor . ⭕Especially when there is a member with the same name in the child parent class, it can be used to indicate that the member in the parent class is called, and the traceback is not limited to the direct parent class. The usage of ⭕ is similar to that of the reference to the object of this class and the identification of the memory space of the parent class.
super
supersuper
superthisthissuper

2. Use

The structure of the parent class can be explicitly called in the child class.

3. Use

3.1 Calling properties and methods

⭕ We can do it in a method or constructor of a subclass. By using " super.属性"or" super.方法", explicitly call the property or method declared in the parent class. However, usually, we are used to omit " super.".

⭕When a property with the same name is defined in the subclass and the parent class, if we want to call the property declared in the parent class in the subclass, we must explicitly use the " super.属性" method to indicate that the call is declared in the parent class. Attributes.

⭕When the subclass rewrites the method in the parent class, when we want to call the overridden method in the parent class in the method of the subclass, we must explicitly use " super.方法" to indicate that the parent class is called. The overridden method in .

3.2 Calling the constructor

(1) By default, all constructors in the subclass will access the constructor with empty parameters in the parent class .

(2) When there is no constructor with empty parameters in the parent class, the constructor of the subclass must specify the call to the corresponding constructor in this class or the parent class through the this (parameter list) or super (parameter list) statement, otherwise a compilation error occurs . At the same time, you can only "choose one of the two", not both, and must be placed in the first line of the constructor.

(3) Among the multiple constructors of a class, at least one of the class constructors uses "super (formal parameter list)" to call the constructor in the parent class.

Code demo:

public class Person {
     
     
    private String name;
    private int age;
    private Date birthDate;
    public Person(String name, int age, Date d) {
     
     
       this.name = name;
       this.age = age;
       this.birthDate = d; }
    public Person(String name, int age) {
     
     
       this(name, age, null);
    }
    public Person(String name, Date d) {
     
     
       this(name, 30, d);
    }
    public Person(String name) {
     
     
       this(name, 30);
    } 
}


public class Student extends Person {
     
     
    private String school;
    public Student(String name, int age, String s) {
     
     
      super(name, age);
      school = s; 
    }
    public Student(String name, String s) {
     
     
      super(name);
      school = s; 
    }
// 编译出错: no super(),系统将调用父类无参数的构造器。
    public Student(String s) {
     
      
      school = s; 
    } 
}

3. The difference between this and super

No. difference this super
1 access property Access the properties in this class, if this class does not have this property, continue to search from the parent class Direct access to properties in the parent class
2 call method Access the method in this class, if this class does not have this method, continue to search from the parent class Direct access to methods in the parent class
3 call the constructor Calling the constructor of this class must be placed in the first line of the constructor Call the superclass constructor, which must be placed in the first line of the subclass constructor

Fourth, the whole process of subclass object instantiation

(1) Judging from the results: (inheritance)
⭕ After the subclass inherits the parent class, it obtains the properties or methods declared in the parent class.
⭕ Create an object of the subclass, in the heap space, all properties declared in the parent class will be loaded.

(2) From a process point of view:
when we create a subclass object through the subclass's constructor, we must directly or indirectly call the superclass's constructor, and then call the superclass's superclass' constructor, ... until java.lang.Objectuntil the constructor of the empty parameter in the class is called . It is because all the structures of the parent class have been loaded , so we can see the structure of the parent class in the memory, and the subclass object can be considered for calling.

(3) Clear: Although the constructor of the parent class is called when the subclass object is created, an object has been created from beginning to end , that is, the newsubclass object.

Guess you like

Origin blog.csdn.net/weixin_52533007/article/details/124136944