Home > Java > javaTutorial > body text

Introduction to the usage of this keyword in Java

PHPz
Release: 2023-04-24 22:13:05
forward
878 people have browsed it

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!