![](/img/trans.png)
[英]How to call a class of instance variables through a method of another class
[英]Call method of a class to use instance of another class
我或多或少是Java的新手。 我的意圖是將一個類的方法“導出”到另一類(以使使用一個實例的所有方法都具有整齊的結構)。 我的問題是,我無法在當前重載的類的實例與放入另一個類的其他方法之間建立必要的連接。
到目前為止,我已經啟動了Graph
類的實例,並將應該用來獲取該實例值的方法放入Readings
。 由於無法確定太多內容,因此在Class
啟動了Readings
實例,並在Graph
創建了一個方法,在Readings
調用了該方法。 到目前為止,還算不錯(我假設),但是問題在於Readings
中的方法並不真正知道如何處理我的Graph
-Instance /在哪里獲取吸氣劑。
static Graph graphToBeWorkedOn;
在Readings
類中並沒有真正的幫助,我得到的只是一個空指針。
在此先感謝您的任何建議/幫助!
編輯: Graph
:
...
Readings readingsVariable = new Reading();
...
public List<SpecificNode> methodToBeCalled(int numberInput) {
List<SpecificNode> listOfMethod = new ArrayList<SpecificNode>();
listOfMethod = readingsVariable.methodOne(numberInput);
return listOfMethod;
}
Readings
:
...
Graph graphToBeWorkedOn;
...
public List<SpecificNode> methodOne(int numberInput) {
List<SpecificNode> listOfMethod = new ArrayList<SpecificNode>();
...
// fails here with a nullPointer:
graphToBeWorkedOn.getSpecificNode(numberInput)
...
return listOfMethod;
}
在測試主體中初始化Graph
並嘗試調用
System.out.println(testGraph.methodOne(2));
從您提供的代碼中,您永遠不會初始化Graph對象。
你需要做
public List<SpecificNode> methodOne(int numberInput) {
graphToBeWorkedOn = new Graph(); // Initialize Graph
List<SpecificNode> listOfMethod = new ArrayList<SpecificNode>();
...
// Now you can call the method
graphToBeWorkedOn.getSpecificNode(numberInput)
...
return listOfMethod;
}
一個簡單的解決方案:使用一個以Graph
對象作為參數的Readings
構造函數,並使用它來初始化graphToBeWorkedOn
字段:
在圖表中:
readingsVariable = new Reading(this);
在閱讀中:
Readings(Graph graphToBeWorkedOn) {
this.graphToBeWorkedOn = graphToBeWorkedOn;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.