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.

Urben
  • 65
  • 5
  • 1
    what do you want to do ? – Ryuzaki L Nov 14 '19 at 19:01
  • Can you not use a setter? – aksappy Nov 14 '19 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. –  Nov 14 '19 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? – Urben Nov 14 '19 at 19:26
  • My first reaction is to implement thus: ```public void allocateArray(int sz) { ar = new Room[sz]; }``` –  Nov 14 '19 at 19:36

1 Answers1

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;
    }
WJS
  • 36,363
  • 4
  • 24
  • 39