This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
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