Cant declare an array of classes outside Main in Java

后端 未结 2 1951
醉酒成梦
醉酒成梦 2021-01-29 08:37

I want to create an array of classes outside Main class, but it won\'t compile. If i put ObjectArray code into Main class everything works fine. I tried making a contructor, ext

2条回答
  •  灰色年华
    2021-01-29 09:34

    The following code should be inside the constructor:

    obj[0] = new Account(); 
    obj[1] = new Account();  
    obj[0].setData(1,2);
    obj[1].setData(3,4);
    

    Also, change the name of toString in ObjectArray to something else e.g. showData. The method name toString conflicts with the one in its default superclass, Object.

    Complete code:

    class ObjectArray {
        Account obj[] = new Account[2];
    
        ObjectArray() {
            obj[0] = new Account();
            obj[1] = new Account();
            obj[0].setData(1, 2);
            obj[1].setData(3, 4);
        }
    
        public void showData() {
            obj[0].showData();
            obj[1].showData();
        }
    }
    
    class Account {
        int a, b;
    
        public void setData(int c, int d) {
            a = c;
            b = d;
        }
    
        public void showData() {
            System.out.println("Value of a =" + a);
            System.out.println("Value of b =" + b);
        }
    }
    
    public class Main {
        public static void main(String args[]) {
            ObjectArray dd = new ObjectArray();
            dd.showData();
        }
    }
    

    Output:

    Value of a =1
    Value of b =2
    Value of a =3
    Value of b =4
    

提交回复
热议问题