Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

The Java this keyword is detailed


May 30, 2021 Article blog


Table of contents


This keyword

The this keyword represents the caller object of the function to which it belongs.

What this keyword does:

  • If there are same member variables and local variables, the default within the method is to access the data of the local variables, you can specify access to the data of the member variables through this keyword;
  • You can call another constructor in one constructor to initialize the object.

Things to watch out for when the this keyword calls other constructors:

  • When the this keyword calls another constructor, the keyword must be the first statement in the constructor;
  • This keyword cannot be called to each other in the constructor because it is a dead loop.

Things to watch out for in this keyword:

  • When there are member variables and local variables with the same name, the internal access to the method is the local variable (java is accessed by the mechanism of the "proximity principle");
  • If a variable is accessed in a method where the value of the variable has a member variable, the java compiler adds the this keyword before the variable.

Things to watch out for when this keyword calls other constructors:

  • When the this keyword calls another constructor, the keyword must be the first statement in the constructor;
  • This keyword cannot be called to each other in the constructor because it is a dead loop.

Recommended lessons: In-depth analysis of Java object-oriented, Java basic getting started to framework practices


This keyword instance

class Student{

INT ID; // ID card

String name; // Name

// Current Savings: There is a member variable of the same name and a local variable, and the local variable is used inside the method.

Public student (int ID, string name) {// The form parameters of a function are also partial variables.

// Call the construction method of a parameter of this class

// this (name); // If you can call the constructor of the following parameters here, you can resolve the problem of duplicate code.

THIS (); // Call the uncommon structure method of this class.

THIS.ID = ID; //this.id = id; the ID of the local variable gives the ID assignment of the member variable.

System.out.println ("Two Parameters Construction Method Call ...");

}

public Student() {

System.out.println ("" None of the construction method is called ... ");

}

public Student(String name) {

this.name = name;

//System.out.println ("The construction method of a parameter is called ...");

}

}

public class Demo1 {

public static void main(String[] args) {

Student S = New Student (110, "Diga");

System.out.println ("Number:" + S.ID + "Name:" + S.Name);

Student s2 = new Student("W3CSCHOOL");

System.out.println ("Name:" + S2.NAME);

}

}