Java类内方法调用、同类型字段及链式调用疑问与Test类问题咨询
Hey there! Let's break down your questions one by one and fix the issue with your Test class code.
1. Method & Field Access in the Same Class
- Calling another method in the same class: Absolutely! You can directly call other methods of the same class using
this.methodName()(or even omitthis.if there's no variable name conflict). This is standard practice in Java for class-internal method calls. - Accessing current-class-type fields: Yes, you can absolutely access fields of the same class type. Just keep in mind: if the field isn't initialized (defaults to
null), trying to access its properties or methods will throw aNullPointerException.
2. Chained Calls for Methods Returning Current Class Type & Your Broken remove() Method
First, the short answer: Yes, you can absolutely write chained calls like this.method1().fields when a method returns an instance of the current class. This is a common pattern (used in builder patterns, for example) where each method returns an object, allowing you to chain subsequent operations.
Now let's figure out why your remove() method isn't working. Let's look at your code:
The Root Cause
Your reAssignKey() method returns the father field, but you never initialize father anywhere in your code. By default, uninitialized object fields in Java are null.
public Test reAssignKey(int input) { key = input; return father; // father is null by default! }
When you run this.reAssignKey(3).Sibling = new Test(3,10);, you're trying to access the Sibling field on a null object (the uninitialized father), which triggers a NullPointerException—that's why your remove() method fails.
Fix Options
Choose one based on your intended logic:
Return the current instance for chained operations on the same object
If you wantreAssignKey()to let you chain operations on the currentTestobject, modify the method to returnthisinstead offather:public Test reAssignKey(int input) { this.key = input; return this; // Return the current instance }Now
this.reAssignKey(3)will return the currentTestobject, and you can safely access itsSiblingfield (just make sure to initializeSiblingif needed, or assign it like you're doing).Initialize the
fatherfield before using it
If you needreAssignKey()to returnfather, make surefatheris initialized first. For example, add initialization in the constructor:public Test(int item, int obj){ this.key = item; this.value = obj; this.father = new Test(0, 0); // Initialize father to a valid Test instance }
Also, a quick note on Java naming conventions: field names should use camelCase (so Sibling should be sibling for better readability).
内容的提问来源于stack exchange,提问作者Gabriel Mike

