Reputation: 27
I have code here that creates a nested class, and then checks to see if a value is there. Answer goes where [???] is currently, the code given to me can't be changed.
//The answer must have balanced parentesis
class A{
class C{
int foo(){return 42;}
}
}
public class Exercise{
public static void main(String [] arg){
assert ([???].foo()==42);
}
}
The question: how do I access the foo() method within C (which is within A)?
Upvotes: 0
Views: 383
Reputation: 6802
dimoniy is correct.
you can also do:
A.C c = new A().new C();
assert (c.foo() == 42);
Upvotes: 0
Reputation: 5995
In order to run a non-static method of class C
, you need to create an instance of C
,but C
is non-static inner class of A and hence you need to create an instance of A
before you can create C
. So, to create A
:
A a = new A();
To create C:
C c = a.new C();
To invoke method foo
c.foo()
All in one line:
new A().new C().foo()
Upvotes: 3