Detailed explanation of the usage of this and super in Java

preface

Keywords in Java last we talked about final, Deep understanding of the final keyword in Java
This time, let's review the usage of this and super keywords. As a java programmer, I think the foundation is the most important, because it determines our upper limit. Therefore, most of my articles focus on sharing the basic knowledge of Java. Learn the foundation well, and the later knowledge will become simple if I want to learn. No more nonsense, enter the text.

this

The this keyword can only be used inside a method to represent a reference to the object calling the method.

In fact, simply speaking, this keyword represents the current object. Let's introduce the usage of this keyword in Java.

1. Call member variable

Inside a class's method, what would we do if we wanted to call its member variable without this?

public class ThisTest {

    private String name = "xiaoming";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        name = name;
    }
}

Looking at the above code, we created a name attribute in ThisTest class, and then created a setName method. Note that the formal parameter of this method is also String name. Will we change the attribute of the member variable name by assigning a value like name = name?

public static void main(String[] args) {
    ThisTest thisTest = new ThisTest();
    thisTest.setName("xiaoma");
    System.out.println(thisTest.getName());
}

The print result is xiaoming instead of xiaoma we reset. Obviously, this method cannot be called to member variables inside the method. Because the name of the formal parameter is the same as the name of the member variable, the name = name inside the setName method. According to the recent principle, the compiler resolves the two name attributes to the formal parameter name by default, so that our setting operation has nothing to do with the name of the member variable. Of course, it can't be set.

The solution is to use the this keyword. We modify the setName method as follows:

public void setName(String name) {
    this.name = name;
}

After calling the above main method for assignment, the printed result is xiaoma.

this represents the current object, that is, the object that calls the method name must be the called member variable.

2. Call constructor

A constructor is a method with the same name as a class. A constructor does not return a value, but it cannot be modified with void. In a class, there must be a constructor. If not, the compiler will automatically add a parameterless constructor for the class when compiling. A class can have multiple constructor methods, which can be distinguished according to parameters when calling.

public class Student {

    private int age;

    private String name;

    public Student() {
        this("pony",50);
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
        System.out.println(name + "this year" + age + "Years old");
    }


    public static void main(String[] args) {
        Student student01 = new Student();
        Student student02 = new Student("Xiaojun",45);
    }
}

Use this("pony", 50) to call another constructor Student(String name, int age) to initialize and assign values to member variables.

Output results:

Pony is 50 years old
 Xiao Jun is 45 years old

Process finished with exit code 0

Note: if you call the constructor through this, you can only put this code on the first line of the constructor, which is the requirement of the compiler, as shown below: putting it on the second line will report an error.

3. Call normal method

this represents the current object, so you can certainly call the normal methods of the current class.

public Student() {
    this.say();
}

public void say(){
    System.out.println("The pony is good at singing.");
}

4. Returns the current object

public class ThisTest {

    public Object newObject(){
        return this;
    }
}

This means that whoever calls the newObject() method returns a reference to who.

super

The super keyword in Java is a reference to a parent class object.

We analyze the reference of the parent class object, which means that we can only use it in the child class. Since it is an object reference, we can also use it to call member properties and member methods. Of course, the super keyword here can also call the constructor of the parent class.

The specific usage is as follows:

1. Call the constructor of the parent class

Inheritance in Java everyone should understand that subclasses inherit from the parent class. We can call the properties and methods of the parent class with the objects of the subclass. We know that properties and methods can only be called through objects, so we can boldly assume that when creating subclass objects, we also create the objects of the parent class, and the objects are created by calling constructors, When we create a subclass object, we should call the constructor of the parent class.

Let's look at this Code:

public class Teacher {

   public Teacher(){
       System.out.println("I am a people's teacher.");
   }
}

class Student extends Teacher {

    public Student(){
        System.out.println("I am a student.");
    }
}

Let's create a subclass object:

public static void main(String[] args) {
    Student s = new Student();
}

Output results:

I am a people's teacher.
I am a student.

Process finished with exit code 0

The print results show that when creating a subclass object, we first call the construction method of the parent class, and then call the construction method of the subclass, that is, when creating a subclass object, we first create a parent class object, which is consistent with our previous conjecture.

Then the question comes again: when is the parent class constructor called?

You can refer to the official Java documentation: https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#d5e14278

If the declared class is the original class Object, the default constructor has an empty body. Otherwise, the default constructor simply calls the superclass constructor without parameters.

In other words, except for the top-level class object The class constructor does not invoke the method of constructing the parent class, and the rest of the classes call the constructor of the parent class by default in the constructor (without explicitly declaring that the subclass of the parent class is Object).

So what is it called through? Let's look at the official documents:

The super class constructor is called through the super keyword and starts with the super keyword.

Therefore, the construction method of the above Student class should actually be as follows:

class Student extends Teacher {

    public Student(){
        super();//The subclass calls the constructor of the parent class through super
        System.out.println("I am a student.");
    }


    public static void main(String[] args) {
        Student s = new Student();
    }
}

By default, the subclass calls the parameterless construction method of the parent class through super(). If the parent class shows that it declares a parameterless construction method but does not declare a parameterless construction method, the instantiated subclass will report an error.

The solution is to call the parameterized constructor of the parent class through the super keyword:

class Student extends Teacher {

    public Student(){
        super("pony");
        System.out.println("I am a student.");
    }


    public static void main(String[] args) {
        Student s = new Student();
    }
}

2. Call the member property of the parent class

public class Teacher {

    public String name = "pony";

    public Teacher() {
        System.out.println("I am a people's teacher.");
    }
}

class Student extends Teacher {

    public Student() {
        System.out.println("I am a student.");
    }

    public void fatherName() {
        System.out.println("My parent class name is:" + super.name);//Call the properties of the parent class
    }

    public static void main(String[] args) {
        Student student = new Student();
        student.fatherName();
    }
}

Output results:

I am a people's teacher.
I am a student.
My parent name is: pony

Process finished with exit code 0

3. Call the method of the parent class

public class Teacher {

    public String name;

    public Teacher() {
        System.out.println("I am a people's teacher.");
    }

    public void setName(String name){
        this.name = name;
    }
}

class Student extends Teacher {

    public Student() {
        super();//Call the constructor of the parent class
        System.out.println("I am a student.");
    }

    public void fatherName() {
        super.setName("Xiaojun");//Call the normal method of the parent class
        System.out.println("My parent class name is:" + super.name);//Call the properties of the parent class
    }

    public static void main(String[] args) {
        Student student = new Student();
        student.fatherName();
    }
}

Output results:

I am a people's teacher.
I am a student.
My parent name is: Xiao Jun

Process finished with exit code 0

4. this and super appear in the same construction method?

Suppose super() precedes the this() keyword

First, call the parent class construction method through super() to instantiate the parent class once. Then call this(), this() method will call the construction method of the subclass, and the parent class will be instantiated again in the construction method of the subclass. In other words, we instantiate the child class once and the parent class twice, so obviously the compiler does not allow it.

Conversely, this() is the same before super(). Moreover, the compiler is limited to this() and super(). These two keywords can only appear in the first line of the construction method. When these two keywords are put together, there is always a keyword in the second line, and the compilation cannot pass.

Similarities and differences between this and super

  • Super (parameter): call a constructor in the base class (should be the first statement in the constructor).
  • This (parameter): call another constructor formed in this class (should be the first statement in the constructor).
  • Super: it refers to the member in the direct parent class of the current object (used to access the member data or function in the hidden parent class in the direct parent class. When the base class and the derived class have the same member definition, such as: super. Variable name, super. Member function name (argument).
  • This: it represents the current object name (where ambiguity is easy to occur in the program, this should be used to indicate the current object; if the formal parameter of the function has the same name as the member data in the class, this should be used to indicate the member variable name).
  • The call to super() must be written in the first line of the subclass construction method, otherwise the compilation will not pass. The first statement of each subclass construction method implicitly calls super(). If the parent class does not have this form of constructor, an error will be reported during compilation.
  • super() is similar to this(). The difference is that super() calls the construction method of the parent class from the subclass, and this() calls other methods in the same class.
  • Both super() and this() need to be placed in the first line of the constructor.
  • Although you can call one constructor with this, you cannot call two.
  • This and super cannot appear in one constructor at the same time, because this must call other constructors, and other constructors must also have super statements. Therefore, if there are the same statements in the same constructor, the meaning of the statements will be lost, and the compiler will not pass.
  • Both this() and super() refer to objects, so they can't be used in static environment. Including: static variable, static method and static statement block.
  • In essence, this is a pointer to this object, while super is a Java keyword.

ending

I am a yard farmer who is being hit and still trying to move forward. If the article is helpful to you, remember to praise and pay attention, thank you!

Keywords: Java

Added by AnsonM on Wed, 05 Jan 2022 21:47:18 +0200