How can i access an object from another method in java?

While interesting, both of the answers listed ignored that fact that the questioner is using static methods. Thus, any class or member variable will not be accessible to the method unless they are also declared static, or referenced statically. This example:

public class MyClass {
    public static String xThing;
    private static void makeThing() {
        String thing = "thing";
        xThing = thing;
        System.out.println(thing);
    }
    private static void makeOtherThing() {
        String otherThing = "otherThing";
        System.out.println(otherThing);
        System.out.println(xThing);
    }
    public static void main(String args[]) {
        makeThing();
        makeOtherThing();
    }
}

Will work, however, it would be better if it was more like this...

public class MyClass {
    private String xThing;
    public void makeThing() {
        String thing = "thing";
        xThing = thing;
        System.out.println(thing);
    }
    public void makeOtherThing() {
        String otherThing = "otherThing";
        System.out.println(otherThing);
        System.out.println(xThing);
    }
    public static void main(String args[]) {
       MyClass myObject = new MyClass();
       myObject.makeThing();
       myObject.makeOtherThing();
    }
}

You would have to make it a class variable. Instead of defining and initializing it in the create() function, define it in the class and initialize it in the create() function.

public class SomeClass {
    NumberList numberlist; // Definition
    ....

Then in your create() function just say:

numberlist= new NumberList(length, offset);  // Initialization

Declare numberList outside your methods like this:

NumberList numberList;

Then inside create() use this to initialise it:

numberList = new NumberList(length, offset);

This means you can access it from any methods in this class.

Tags:

Java