Cant declare an array of classes outside Main in Java

后端 未结 2 1909
醉酒成梦
醉酒成梦 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:20

    You cannot have code directly in a class. It needs to be in a method, constructor, or initializer block.

    Here, you'd put the code in an initializer block:

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

    I would however recommend creating a constructor to initialize the object, and then use an array initializer.

    You also need to rename the void toString() method, since it clashes with the String toString() method inherited from Object.

    In the following code I have also added various spaces to format according to standard style guidelines. Makes the code easier to read.

    class Main {
        public static void main(String args[]) {
            ObjectArray dd = new ObjectArray();
            dd.show();
        }
    }
    class ObjectArray {
        Account[] obj = { new Account(1, 2), new Account(3, 4) };
    
        public void show() {
            obj[0].showData();
            obj[1].showData();
        }
    }
    class Account {
        private int a, b;
    
        public Account() {
        }
        public Account(int c, int d) {
            a = c;
            b = d;
        }
        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);
        }
    }
    

    Output

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

提交回复
热议问题