Java inner/anon classes

39 Views Asked by At

I'm stuck on this question where we need to instantiate the C class through A

class A{
  static class B{}
  static class C{ B b;
    C(B b){this.b=b;}
    int foo(){return 42;}
  }
}
public class Exercise{

  public static void main(String [] arg){
    assert ([???].foo()==42);
  }
}     

Obviously we need to instantiate the C class within the A class, however I tried doing something like A.C(new B b) and a few other variations, but I can't seem to figure it out, does anyone have any suggestions?

1

There are 1 best solutions below

0
Reilas On

You'll need an instance of B, to instantiate C

A.B b = new A.B();
A.C c = new A.C(b);
assert c.foo() == 42;

Or, simplified.

assert new A.C(new A.B()).foo() == 42;

If a class contains no constructor, an empty constructor is inferred.