Home Java javaTutorial Detailed explanation of Java keyword this (power node arrangement)

Detailed explanation of Java keyword this (power node arrangement)

Mar 31, 2017 am 10:28 AM

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();
 }
}
Copy after login

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();
}
Copy after login

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();
 }
}
Copy after login

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 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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles