關于創建一個編輯類物件中的值的方法,我有一個快速且最可能是簡單的問題。貝婁是一個高度簡化的例子。有一個名為“num”的類,其中包含一個名為 obj 的整數。num() 方法接受并分配一個整數的輸入。我需要一種方法來通過添加 1 來編輯該 obj 值,該值可以像這樣構造:num testcase=new num(4).addone(); 或者簡單地說:num(4).addone(); 我知道還有其他方法可以做到這一點,但不幸的是我需要這樣做。我想要的輸出是一個新的“num”物件,其中包含存盤在 obj 中的整數值 5。本質上,我需要創建物件,然后通過添加 1 進行編輯。如果有人可以為我提供解決方案,給我正確的術語以供進一步研究,或者任何幫助將不勝感激。我知道下面的例子不起作用,但我只是舉了一個例子。感謝您提供任何幫助。
public static class num{
//simple class containing single integer
int obj;
public num(int input){
//method creating num class object
this.obj=input;
}
public addone(){
//rudimentary attempt at creating such function.
this.obj=obj 1;
}
}
public static void main(String[] args) {
System.out.println("Hello World!");
num testcase=new num(4).addone();
}
}
我嘗試了多種不同的方法來存盤函式并嘗試實作 newinstance 但不太了解這一點。
uj5u.com熱心網友回復:
為了讓您進行鏈式方法呼叫,您需要您的方法實際回傳您的類本身的實體,以便它可以決議為賦值指令。
這里:
public class num {
int obj;
public num(int input){
this.obj=input;
}
//it needs to return the instance of the class itself
public num addone(){
this.obj=obj 1; //modify the obj attribute
return this; //return the instance of the class
}
public static void main(String[] args) {
System.out.println("Hello World!");
//Reason you need addone to return the instance of the class
//is for the compile to resolve the below assignment as
//you are assigning a Type "num" to testcase
num testcase = new num(4).addone();
System.out.println(testcase.obj); //this should print 5
}
}
這是一個很好的讀物:https ://www.geeksforgeeks.org/method-chaining-in-java-with-examples/
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/537392.html
標籤:爪哇哎呀
下一篇:從父類陣列C 回傳子類
