【问题标题】:Create object in correct scope在正确的范围内创建对象
【发布时间】:2018-02-13 03:39:13
【问题描述】:

因为我在 A 类内部的方法中创建对象,所以当我需要在另一个方法(A 内部)中使用对象的方法时,它超出了范围。我想在方法中创建对象的原因是因为创建的对象数量取决于用户输入。

有没有办法可以在方法之外使用对象?

public class A {
    //I was thinking I could write something here to change the scope?
    // Like: public B objekt

    public static ArrayList input(){
        input0 = reader.nextInt();

        for(int i=0; i<input0; i++){
            //user inputs: input1 & and input2
            B object = new B(input1, input2);
            list.add(objekt)
        }

        return list
    }

    public static void doSomething(ArrayList list){
        //Because the objekt is out of scope. I cannot call the method.
        list.get(index).get_input1();
    }

    public static void main(String[] args) {
        list = A.input()
        A.doSomething(list);
    }
}

public class B {
    public int input1;
    public int input2;

    public B(int input1, int input2){
        this.input1 = input1;
        this.input2 = input2;
     }

     public int get_input1(){
         return input1;
     }
}

【问题讨论】:

  • ArrayList 更改为ArrayList&lt;B&gt;
  • 只需创建一个静态类字段,您就可以从任何方法访问它。
  • list 在哪里定义?我们可以看到它在哪里使用,但您没有显示它是在哪里定义或构造的。另外,请显示可编译的代码,或仅针对您所询问的问题破坏编译器。

标签: java object scope


【解决方案1】:

我假设您的列表定义为:

Arraylist List = new ArrayList();

您遇到的问题与您创建B 对象的范围无关。

相反,该列表包含Object 类型的对象,因此您不能在Object 上调用get_input1()

如果您将列表的定义更改为:

List<B> list = new ArrayList<>();

...以及您的方法签名:

public static List<B> input() {

...那么您就可以在列表中的对象上调用get_input1()

当然,您需要修复代码中的其他小编译问题才能使其编译。

【讨论】:

    猜你喜欢
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多