Home java The this keyword in java

The this keyword in java

Author

Date

Category

I started learning java and came across the word this but did not really understand what it is for. But I already know python and I have a question is the word this in java the same as the word self in python?


Answer 1, authority 100%

Java uses the word this with two different meanings.

1) When used as an object type variable such as this.value = 5; , it means the object to which the code using this refers. This is used to resolve ambiguity when, for example, there is an object field and a local variable with the same name, then simply qq ++ means the increment of the local variable qq , and this.qq ++ means the increment of the object field of the same name. Sometimes it can be used simply to improve readability. Quite often you can find such use of it in constructors, when the names of the parameters of the constructor coincide with the names of fields of this type:

class Person {
 private String name; // Object fields
 private int age;
 // Create an object with the given field values
 public Person (String name, int age) {// When calling, set initial values ​​as parameters
  this.name = name; // Values ​​of these parameters
  this.age = age; // assigned to object variables
 }
}

It is clear that it cannot be used in static methods, since static methods do not belong to any separate object.

2) It can be used in a constructor in the form of a method call such as this (someValue) , in which case it means calling another constructor of the same class. Used to shorten code when two different constructors need to do the same thing, e.g.

class Person {
 private String name; // Object fields
 private int age;
 public Person (String name, int age) {// Create an object with the specified field values
  this.name = name; // Parameter values
  this.age = age; // assigned to object variables
 }
 public Person () {// Create an object with some default values
  this ("NoName", -1); // Call another constructor
 }
}

In this example, the job of the second constructor is simply to provide some field values ​​if the user didn’t provide them. With these values, the second constructor calls the first constructor, which assigns the resulting values ​​to the corresponding fields.

P.S. Yes, the answer about C++ mentioned in the comment by AivanF reminded me of another important point – using this is the only way for an object to pass itself as a parameter when calling a method, or return itself as a result of execution method:

public MyClass registeredSelf () {
 registrator.register (this); // Register me
 this.registered = true;
 return this;
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions