search
HomeJavajavaTutorialDetailed explanation of Java keyword this (power node arrangement)

This in java can be seen everywhere and has many uses. Under normal circumstances, it is easy to understand this keyword. However, when I first started learning, I had a question that I could not clearly understand. Now I slowly understand it. I will record it for everyone through this article for reference by friends in need. Next

When we usually use the this keyword in Java, we all know that this represents the current instance of the method that is calling this class. Under normal circumstances, it is easy to understand this keyword, but when I first started learning, I had a question that I couldn't clearly understand. Now that I understand it slowly, I want to write it down. Maybe someone has the same problem as me. Question, maybe it can help others. Let’s first briefly look at the role of this under normal circumstances. For example, the following code:

public class Leaf {
 private int i = 0;
 Leaf increment() {
  i++;
  return this;
 }
 void print() {
  System.out.println("i = " + i);
 }
 public static void main(String[] args) {
  Leaf x = new Leaf();
  x.increment().increment().print();
 }
}

In the main method of the Leaf class, we create a new Leaf instance x, and then the x instance calls the increment() method. If increment() is a normal method or void method, there is nothing worth studying in this place. What's special is that in the increment() method, what we return is this, and this this represents the x we ​​just created. Because x is calling the increment() method, increment()method this obviously represents the x instance of Leaf.

There seems to be nothing to discuss. This represents the instance x that calls the method. However, if we modify the main()function to look like the following

public static void main(String[] args) {
 Leaf x = new Leaf();
 x.increment().increment().print();
  
 Leaf y = new Leaf();
 y.increment().increment().print();
}

In the above modified code, we create a new Leaf instance y, and then y also calls two consecutive calls. timesincrement(). Now the question is, if x and y call the increment() method at the same time, then who does this represent? You may think there is something wrong with this. When x calls the increment() method, this represents x. When y calls the increment() method, this represents y. But the problem is that when we talk about calling methods, at the jvm level we find the memory address where the increment() method in the Leaf class is located, and then create a stack frame in the java virtual machine stack.

Then execute the code in the method in the stack frame. Now you see, that is to say, at the jvm execution method level, there is no so-called x call, y is called. So, how does this in the method determine which instance it points to?

Let’s take a look at how it is displayed in the Leaf class bytecode to see if we have missed anything. If we do not pass the x instance or y instance into the method, then, execute the method in the jvm , it is impossible to know which instance this specifically points to.

Here, we see that in the increment() method, there are no parameters in the encoding, but the number of parameters is shown as 1 in the bytecode. Think about it carefully , the result is already obvious: when JVM performs compilation, in the instance method, a parameter will be passed hidden by default, and this parameter is the currently called instance itself. For example, if x is called, x will be passed when hidden, and if y is called, y will be passed. Therefore, our this can determine who it points to at the jvm execution method level.

The above conclusion is our own inference. Is there any book that describes this in detail? In "java Programming Thoughts", this section is described as follows:

Suppose we are inside a method and want to get the handle of the current object . Since that handle is passed "secretly" by the compiler, no identifier is available. However, there is a dedicated keyword for this purpose: this.

The handle secretly passed by the compiler mentioned in it is the hidden parameter we have here.

So far, the description of this must be very clear, and we understand it at the jvm level. So, are you interested in taking a look at the example below and thinking about what this in base class B represents?

public class B {
 public B() {
  System.out.println(this.getClass().getSimpleName()); 
  System.out.println(((A) this).a); 
 }
}
public class A extends B {
 public int a = 100;  
 public A() {
  a = 200;
 } 
 public static void main(String[] args) {
  new A();
 }
}

This example was originally intended to understand how a class is initialized when java has a inheritance structure, but the constructor in class B is quite special. : The SimpleName output by this in the constructor in class B is A. Usually when we encounter the situation, the SimpleName output by this in class B should be B, but here it is A? Why?

In the process of talking about this above, we have already touched on this. When calling the java method to create a stack frame, the jvm will secretly pass a current instance. Therefore, when we execute the constructor of A, the constructor of parent class B will be called by default. When calling the constructor of parent class B, the current instance passed in secretly is the instance of A - because it is B is called in the constructor of A, so this here represents A instead.

The above is the detailed content of Detailed explanation of Java keyword this (power node arrangement). For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment