Java
javaTutorial
Java custom class method chain calling: design and implementation of object state modification
Java custom class method chain calling: design and implementation of object state modification

Understanding method chaining
In Java programming, method chaining is a common programming paradigm that allows multiple methods to be called continuously in the same line of code. This mode is usually used in the Builder mode, the Fluent API, or a series of operations on the same object. The core idea is that each method returns the current object instance after performing its function, allowing the next method to act directly on this returned object.
Consider a simple custom class num that contains an integer field obj. We want to create a method addone(), which can add 1 to the value of obj and can be used in a chain call, for example: new num(4).addone().
An initial attempt might look like this:
public class num {
int obj;
public num(int input) {
this.obj = input;
}
// Wrong implementation: no return value public addone() {
this.obj = obj 1;
}
public static void main(String[] args) {
// Compilation error: addone() has no return value and cannot be chained or assigned // num testcase = new num(4).addone();
// System.out.println("Hello World!");
}
}
The addone() method in the above code does not specify a return type, and the default is void. This means that after calling new num(4).addone(), the addone() method does not return any object, causing the expression to be unable to continue the chain call, and the result cannot be assigned to the variable testcase of type num, so a compilation error will occur.
Implement object state modification and chain calls
To implement method chain calling, the key is that methods that modify the object state (such as addone()) must return the current object instance. In Java, this is done via the keyword this. this represents the object itself on which the current method is called.
Modify the addone() method to return num type and return this:
public class num {
int obj;
public num(int input) {
this.obj = input;
}
// Correct implementation: Returns the current object instance, allowing chained calls to public num addone() {
this.obj = obj 1; // Modify the internal state of the object return this; // Return the current object instance}
public static void main(String[] args) {
System.out.println("Demo method chain call:");
//Example 1: Create an object and call the modification method in a chain, and then assign the value num testcase = new num(4).addone();
System.out.println("The value of testcase.obj is: " testcase.obj); // Output 5
//Example 2: Call multiple modification methods in a continuous chain (if they exist)
// num anotherCase = new num(10).addone().addanotherMethod(); // Assume there is addanotherMethod()
// System.out.println("The value of anotherCase.obj is: " anotherCase.obj);
// Example 3: Use the chain call result directly in the expression System.out.println("Direct chain call result: " new num(9).addone().obj); // Output 10
}
}
In the above revised code, the addone() method is declared to return the num type, and after modifying the value of obj, the current num object instance is returned through return this;. In this way, the final result of the expression new num(4).addone() is an object of type num (its obj value is 5), so it can be successfully assigned to the num testcase variable, or continue to call other methods on the object.
Principle analysis
When executing new num(4).addone(), its internal execution flow is as follows:
- new num(4): First create a new instance of the num class, call its constructor, and initialize obj to 4. This operation returns a num object.
- .addone(): Immediately afterwards, call the addone() method on the num object returned in step 1.
- Inside the addone() method, this.obj = obj 1; changes the obj value of the current object from 4 to 5.
- return this;: The addone() method returns the current object instance (that is, the num object whose obj has been modified to 5).
- Ultimately, the evaluation result of the entire expression new num(4).addone() is the num object with obj value 5. This result can be assigned to a variable of type num, or other methods can be called on it.
Application scenarios and precautions
Method chaining is very popular in Java, especially suitable for the following scenarios:
- Builder Pattern : When a class has too many constructor parameters or the object creation process is complex, you can use the builder pattern to set the properties of the object through a series of chain-called withXxx() methods, and finally create the final object through the build() method.
- Configuration object : When configuring the framework or library, set various parameters through chain calls.
- Streaming API : For example, Java 8 Stream API, a series of operations (filter().map().collect()) are called in a chain.
- State modification : As shown in this example, a series of modification operations are performed on the object.
Things to note:
- Return type consistency : All methods participating in the chain call must return the current object instance (this), otherwise the chain will be interrupted.
- Readability : Although chained calls can make the code more concise, too long chains may reduce the readability of the code. A balance should be found between brevity and readability.
- Immutable Object : If your goal is to create an immutable object (Immutable Object), then the modify method should not return this, but should return a new object instance containing the modified state. The examples in this tutorial are for Mutable Objects.
Summarize
We can easily implement method chaining in Java by letting methods that modify the object's state return the current object instance (this). This mode not only makes the code more compact and expressive, but also improves development efficiency and code readability. It is one of the key technologies for designing fluent APIs. Understanding and properly using return this; is an important step in mastering method chain calling in Java object-oriented programming.
The above is the detailed content of Java custom class method chain calling: design and implementation of object state modification. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20528
7
13637
4
What is exception masking (Suppressed Exceptions) in Java_Multiple resource shutdown exception handling
Mar 10, 2026 pm 06:57 PM
What is SuppressedException: It is not "swallowed", but actively archived by the JVM. SuppressedException is not an exception loss, but the JVM quietly attaches the secondary exception to the main exception under the premise that "only one exception must be thrown" for you to verify afterwards. It is automatically triggered by the JVM in only two scenarios: one is that the resource closure in try-with-resources fails, and the other is that you manually call addSuppressed() in finally. The key difference is: the former is fully automatic and safe; the latter requires you to keep it to yourself, and it can be written as shadowing if you are not careful. try-
How to configure Java's log output environment_Logback and Log4j2 integration solution
Mar 10, 2026 pm 08:39 PM
They cannot be used together - Logback and Log4j2 are mutually exclusive, and SLF4J only allows one binding to take effect; if they exist at the same time, a warning will be triggered and one of them will be randomly selected, resulting in log loss or abnormal behavior. A unified appearance and single implementation are required.
How to hot deploy Java applications in IDEA_JRebel plug-in installation and activation tutorial
Mar 10, 2026 pm 08:01 PM
JRebel has basically failed in modern Java development because of its underlying mechanism conflicts with the Java9 module system, SpringBoot2.4 and mainstream IDEs, while IDEA's built-in HotSwap spring-boot-devtools combination is more stable and reliable.
What is the core role of the collection framework in Java_Analysis of the original intention of Java collection design
Mar 11, 2026 pm 09:01 PM
The core of the Java collection framework is to solve the three major shortcomings of fixed array length, type insecurity, and redundant operations; it abstracts data relationships through interfaces (Collection is a "bundle of things", Map is "mapping rules"), and generics ensure compilation-time type safety, but implementation class switching may cause implicit performance degradation.
How to configure Java hotkeys in IntelliJ IDEA_Common shortcut key customization guide
Mar 10, 2026 pm 08:06 PM
In IDEA, Ctrl Alt L defaults to "ReformatCode", which can be changed to other operations: first check for conflicts in the Keymap, then remove the original binding and add a new shortcut key for the target operation; pay attention to the focus position, file type and plug-in interference; Mac needs to troubleshoot system-level interception; when team collaboration, the Scheme should be unified and the settings should be synchronized with SettingsRepository.
How to deploy Java production environment on Windows Server_Security enhancement and service-oriented configuration
Mar 11, 2026 pm 07:18 PM
The boundary between Java version selection and JRE/JDK must be clearly defined in the production environment. Do not use JDK. JRE must be installed on Windows Server—unless you really need diagnostic tools such as jps and jstack to run in the service process. The java.exe and javaw.exe that come with the JDK have the same behavior, but the extra bin directory in the JDK will increase the attack surface. Especially when misconfigured PATH causes the script to call javac.exe, it may be used to execute compiled malicious payloads. Download the build with jdk-xx.jre suffix from https://adoptium.net/ (such as temurin-17.0.2 8-jre), which is not the jdk package installation path.
JavaFX: Copy string contents to system clipboard
Mar 13, 2026 am 04:12 AM
This article details how to copy string contents to the system clipboard in a JavaFX application. By utilizing the javafx.scene.input.Clipboard and javafx.scene.input.ClipboardContent classes, developers can easily implement clipboard operations on text data. The article provides clear sample code and usage guidelines to ensure that readers can quickly master and apply this feature in their own projects to improve user experience.
Optimize the Controller layer: introduce DTO mapping and service calling abstraction layer
Apr 03, 2026 am 10:00 AM
This article discusses the introduction of an abstraction layer between the Controller and business services in order to solve the problems of overloaded responsibilities and code duplication in the Controller layer in Web application development. This layer is mainly responsible for the mapping of request DTOs and service input DTOs, service calls, and the mapping of service output DTOs and response DTOs. It achieves generalization through generic and functional programming, thereby improving the cleanliness, maintainability and testability of the code.





