0

I have this child class:

class ChildClass {

    public class Room{
      int size;

      public void On(int size){
        this.size = v;
      }
    }
    public Room[] ar;   
}

And I try to initialize ar in my main method:

public class JavaOnlineCompiler {

    public static void main(String args[]) {      
        ChildClass cc = new ChildClass();

        ChildClass.ar = cc.new Room[]{ //attempt to initialize arr
            new Room(10), new Room(29)  
        };
    }
}

But it isn't working this way. What am I doing wrong?

I am referring to ar inside methods of ChildClass which is why I don't want to define the array outside of ChildClass.

5
  • 1
    what do you want to do ? Commented Nov 14, 2019 at 19:01
  • Can you not use a setter? Commented Nov 14, 2019 at 19:01
  • This is not really a good design. ChildClass fails to construct itself but relies on an external entity to allocate the array. Preferably the ChildClass ctor should do this; failing that, ChildClass should provide something like a 'allocateArray(int size)' method rather than having some unrelated coded poking at its data. Commented Nov 14, 2019 at 19:20
  • @another-dave So you suggest that I put the initialization inside a ChildClass method which has an Int array (in this case as the object only consists of a single Int) as a parameter? Commented Nov 14, 2019 at 19:26
  • My first reaction is to implement thus: public void allocateArray(int sz) { ar = new Room[sz]; } Commented Nov 14, 2019 at 19:36

1 Answer 1

1

You had some typos in your classes. Do it like this.


    public class JavaOnlineCompiler {

       public static void main(String[] args) {
          ChildClass cc = new ChildClass();

          cc.ar = new Room[] { // attempt to initialize arr
                cc.new Room(10), cc.new Room(29)
          };
       }

    }

    class ChildClass {

       public class Room {
          int size;

          public Room(int v) {
             this.size = v;
          }
       }

       public Room[] ar;
    }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.