在正确的范围内创建对象

时间:2017-09-04 22:50:45

标签: java object scope

因为我在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;
     }
}

1 个答案:

答案 0 :(得分:0)

我假设您的列表定义为:

Arraylist List = new ArrayList();

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

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

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

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

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

public static List<B> input() {

...然后你就可以在列表中的对象上调用get_input1()

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