True or False? An instance of a non static inner class always has an associated instance of the enclosing class. I think it's false because a non static inner class may be a inner class defined in a method. A inner class defined in a method doesn't have an associated instance of the enclosing class, correct? Ada
Ada Wang
Greenhorn
Joined: Aug 28, 2000
Posts: 23
posted
0
Could anyone tell true or false? Ada
Paul A
Ranch Hand
Joined: Aug 25, 2000
Posts: 44
posted
0
Complie and run the following code... //=================================================== public class MethodInnerClassTest { String str = "Outer Class"; public void someMethod() { class Inner { public void im1() { System.out.println(" Accessing outer's fields "+MethodInnerClassTest.this.str); } } Inner in = new Inner(); in.im1(); } public static void main(String[] args) { MethodInnerClassTest mt = new MethodInnerClassTest(); mt.someMethod(); } } //=================================================== This defines and instantiates an inner class in a method and then tries to access our class's field. This shows that even if the inner class is inside a method, it has a reference to it's outer class instance.
You're right. To access the inner class of a method, we must create an instance of the enclosing class, from which we may access the method and the inner class of it. Thanks Paul. Ada
Ada Wang
Greenhorn
Joined: Aug 28, 2000
Posts: 23
posted
0
Paul, I modified your code. This time we don't have to create any instances of the enclosing class. =========================================================== public class MethodInnerClassTest{
static String str = "Outer Class";
public static void someMethod(){ class Inner{ public void im1(){ System.out.println(" Accessing outer's fields " + MethodInnerClassTest.str); } } Inner in = new Inner(); in.im1(); } public static void main(String[] args){ //MethodInnerClassTest mt = new MethodInnerClassTest(); //mt.someMethod(); someMethod(); } } ========================================================== From above, the answer should be false.
mmkris_1
Greenhorn
Joined: Jun 18, 2000
Posts: 15
posted
0
When u changed u made the method to be static. So it can be called directly without an instance of the outer object. In fact this can be done directly by declaring the inner class itself static. So the answer is basically true not false.