【问题标题】:How can i access an object from another method in java?如何从 java 中的另一个方法访问对象?
【发布时间】:2015-04-16 15:06:06
【问题描述】:

我有我在 create() 方法中创建的对象编号列表,我想访问它以便可以在 question() 方法中使用它。

还有其他我可能错过的方法吗?我在搞砸什么吗?如果没有,我该怎么做才能获得与以下相同的功能?

private static void create() {
    Scanner input = new Scanner(System.in);

    int length,offset;

    System.out.print("Input the size of the numbers : ");
     length = input.nextInt();

     System.out.print("Input the Offset : ");
     offset = input.nextInt();

    NumberList numberlist= new NumberList(length, offset);




}


private static void question(){
    Scanner input = new Scanner(System.in);

    System.out.print("Please enter a command or type ?: ");
    String c = input.nextLine();

    if (c.equals("a")){ 
        create();       
    }else if(c.equals("b")){
         numberlist.flip();   \\ error
    }else if(c.equals("c")){
        numberlist.shuffle(); \\ error
    }else if(c.equals("d")){
        numberlist.printInfo(); \\ error
    }
}

【问题讨论】:

  • 将其声明为字段,而不是您方法中的局部变量。

标签: java


【解决方案1】:

虽然很有趣,但列出的两个答案都忽略了提问者使用静态方法这一事实。因此,除非它们也被声明为静态或静态引用,否则该方法将无法访问任何类或成员变量。 这个例子:

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();
    }
}

会起作用,但是,如果它更像这样会更好......

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();
    }
}

【讨论】:

    【解决方案2】:

    您必须将其设为类变量。与其在 create() 函数中定义和初始化,不如在类中定义并在 create() 函数中初始化。

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

    然后在你的 create() 函数中说:

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

    【讨论】:

      【解决方案3】:

      在您的方法之外声明numberList,如下所示:

      NumberList numberList;
      

      然后在create()里面用这个来初始化它:

      numberList = new NumberList(length, offset);
      

      这意味着您可以从此类中的任何方法访问它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-11
        • 1970-01-01
        • 2014-08-17
        • 1970-01-01
        • 1970-01-01
        • 2011-08-11
        相关资源
        最近更新 更多