NewbieLearner
NewbieLearner

Reputation: 95

Declaring an array of array using Objects

I'm trying to construct an array of array using Objects. I created the Object Block which contains multiple variables in it. I wrote:

Block[][] block = new Block[4][4];

Now I am having an error when I insert:

block[1][1] = new Block(); // As what I've understood, we still need 
                           // to create the object inside this specific block[][]

The error message is:

Cannot find symbol, ']' expected and Invalid method declaration, return type required

Upvotes: 0

Views: 104

Answers (1)

swemon
swemon

Reputation: 5946

It works for me

public class testProgram {

    public static void main(String args[]) {
        Block[][] block = new Block[4][4];
        block[1][1] = new Block();
        block[1][1].setName("Block 1 1");
        System.out.println(block[1][1].getName());

        block[1][2] = new Block();
        block[1][2].setName("Block 1 2");
        System.out.println(block[1][2].getName());
    }

    public static class Block {

        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

Upvotes: 4

Related Questions