Hi, I just started a new topic - inner class. I understand the concept of static inner class. But, I don't understand the member inner class. Here is an example that I need help for explanation:
Why the outcome is 40? I do not understand F.this.x = y and when should I use enclosing instance? Thanks in advance. Andrew [This message has been edited by Cindy Glass (edited December 18, 2001).]
Joined: Jan 09, 2001
Hi Andrew, Using an member inner class is just another way to encapsulate some implementation that might vary slightly from your outer class. You have created a method in the outer class that just calls the inner class method. This is not required when you create an inner class. You can get the same result using the following call inside your main method: System.out.println( new Fo().new Bar().getValue() ); You will need an outer instance anytime you are inside any static method that requires an object of the inner class. This means that inside your main (a static method) we can't do the following: new Bar(); because we don't have an object of the outer class. We need to create one as the System.out.println method does above. However, if we create another method in the outer class:
We can just call new Bar() because we implicitly have an object of Fo (ourselves). Since the method is non-static an implicit this variable is assumed in front of any method call. Using all the approaches we can show the whole thing below.
Why does the answer equal 40? Well that is the answer to: private int x = 8; // Assigned by compiler upon creation of Bar object private int y = 5; // Assigned by compiler upon creation of Fo 8 * 5 = 40. Since the method is inside the Bar class the x that it will use will be its' own. Because, as stated above, this is implicitly placed in from of x. Since if we just use x inside the Bar class we only see the one defined inside the Bar class, we need some way of getting to the class variables of the outer class. Java gives us the way by using the following notation: <outer class>.this.<variable> Regards, Manfred.
Joined: Nov 12, 2001
Hi Manfred, You are very great. The example is explanatory (expecially those code in main method) and I understand it now. Regards Andrew