简体   繁体   中英

Call method of a class to use instance of another class

I'm more or less new to 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 . 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 . 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.

static Graph graphToBeWorkedOn;

in the Readings class does not really help and all I get is a nullpointer.

Thanks in advance for any advices/help!

Edit: 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;
}

Initilized a Graph in a test-main and attempting to call

System.out.println(testGraph.methodOne(2));

From your provided code, you never initialize the Graph object.

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:

in Graph:

readingsVariable = new Reading(this);

in Readings:

Readings(Graph graphToBeWorkedOn) {
    this.graphToBeWorkedOn = graphToBeWorkedOn;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM