Home  >  Article  >  Java  >  Introduction to the usage of this keyword in Java

Introduction to the usage of this keyword in Java

PHPz
PHPzforward
2023-04-24 22:13:05901browse

Usage of this in java:

1. This generally refers to its own implicit pointer, that is, which object calls the method where this is located.

Example code: TestThis_1.java

/* Question: What is this

* Output result:

* A@4e44ac6a

*/

public class TestThis_1 {

public static void main(String[] args) {

A aa = new A();

System.out.println (aa.f()); //aa.f(), returns the reference (pointer) of the object aa

}

}

class A {

public A f() {

return this; / /Returns a reference to the class A object of the object that called the f() method

}

}

Introduction to the usage of this keyword in Java

2. Distinguish variables with the same name.

Example code: TestThis_2.java

/* Common usage of this 1: Distinguish variables with the same name

* Output result:

* this. i = 1

* i = 33

*/

public class TestThis_2 {

public static void main(String[] args) {

A aa = new A(33);

}

}

class A {

public int i = 1; //This i is a member variable

/*Note: Generally not written this way, the constructor is mainly for initialization. This is mainly written for ease of understanding*/

public A(int i) { //This i is a local variable

System.out .printf("this. i = %d\n", this.i); //this.i refers to the member variable i of the object itself

System.out.printf ("i = %d\n", i); //i here is the local variable i

}

}

Introduction to the usage of this keyword in Java

The above is the detailed content of Introduction to the usage of this keyword in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete