如何从java中的另一个方法访问对象? [英] How can i access an object from another method in java?

查看:334
本文介绍了如何从java中的另一个方法访问对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 a way to do this that I'm missing, or am I just messing something up? If not, how should I go about doing this to enable me to get the same functionality as below?

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


推荐答案

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

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

这篇关于如何从java中的另一个方法访问对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆