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

前端 未结 3 860
孤城傲影
孤城傲影 2020-12-10 17:08

I have the object numberlist that i created in create() method and i want to access it so i can use it in the question() method.

Is there another way to do this that

相关标签:
3条回答
  • 2020-12-10 17:39

    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.

    0 讨论(0)
  • 2020-12-10 17:47

    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
    
    0 讨论(0)
  • 2020-12-10 17:59

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题