[英]Call method of a class to use instance of another class
I'm more or less new to Java. 我或多或少是Java的新手。 My intention is to "export" methods of one class into another class (to have a neat structure of all the methods working with one instance). 我的意图是将一个类的方法“导出”到另一类(以使使用一个实例的所有方法都具有整齐的结构)。 My problem is that I cannot establish the necessary connection between the instance of my currently overloaded class and the additional methods I put into another class. 我的问题是,我无法在当前重载的类的实例与放入另一个类的其他方法之间建立必要的连接。
So far I've initiated an instance of my class Graph
and put methods that are just supposed to get values of that instance into Readings
. 到目前为止,我已经启动了Graph
类的实例,并将应该用来获取该实例值的方法放入Readings
。 Since I could not figure out much I initiated and instance of Readings
in Class
, created a method in Graph
calling a method in Readings
. 由于无法确定太多内容,因此在Class
启动了Readings
实例,并在Graph
创建了一个方法,在Readings
调用了该方法。 So far, so good (I assume) but the problem is that the method in Readings
does not really know how to handle the getters of my Graph
-Instance/where to access the getters. 到目前为止,还算不错(我假设),但是问题在于Readings
中的方法并不真正知道如何处理我的Graph
-Instance /在哪里获取吸气剂。
static Graph graphToBeWorkedOn;
in the Readings
class does not really help and all I get is a nullpointer. 在Readings
类中并没有真正的帮助,我得到的只是一个空指针。
Thanks in advance for any advices/help! 在此先感谢您的任何建议/帮助!
Edit: Graph
: 编辑: Graph
:
...
Readings readingsVariable = new Reading();
...
public List<SpecificNode> methodToBeCalled(int numberInput) {
List<SpecificNode> listOfMethod = new ArrayList<SpecificNode>();
listOfMethod = readingsVariable.methodOne(numberInput);
return listOfMethod;
}
Readings
: 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;
}
Initilized a Graph
in a test-main and attempting to call 在测试主体中初始化Graph
并尝试调用
System.out.println(testGraph.methodOne(2));
From your provided code, you never initialize the Graph object. 从您提供的代码中,您永远不会初始化Graph对象。
You'll need to do 你需要做
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;
}
Simple solution: use a Readings
constructor that takes a Graph
object as parameter and use it to initialize your graphToBeWorkedOn
field: 一个简单的解决方案:使用一个以Graph
对象作为参数的Readings
构造函数,并使用它来初始化graphToBeWorkedOn
字段:
in Graph: 在图表中:
readingsVariable = new Reading(this);
in Readings: 在阅读中:
Readings(Graph graphToBeWorkedOn) {
this.graphToBeWorkedOn = graphToBeWorkedOn;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.