如何从java中的另一个方法访问对象?

我有我在create()方法中创建的对象numberlist,我想访问它,所以我可以在question()方法中使用它。

有没有办法做到这一点,我错过了,或者我只是搞砸了什么? 如果没有,我该怎么做才能让我获得与下面相同的function?

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 } } 

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

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

你必须使它成为一个类变量。 不是在create()函数中定义和初始化它,而是在类中定义它并在create()函数中初始化它。

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

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

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

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

 NumberList numberList; 

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

 numberList = new NumberList(length, offset); 

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