1

If I have the following class

    public class Foo {
       public void bar(){
           fooBar();
       }
       private void fooBar(){
           System.out.println("text...");
       }
    }

instead I can also do something like

    public class Foo {

        public void bar() {
             new inner().fooBar();
        }

        private class inner {
             private void fooBar() {
                   System.out.println(" text ...");
             }
        }

    } 

when should I use inner classes instead of private method? If the functionality is specific to the class Foo then it make sense to use an inner class but the same can also be achieve d through private method which can only be accessed within the class itself.

user2720864
  • 8,015
  • 5
  • 48
  • 60
  • Use an inner class if you want to group data related to eachother that should only be used in the scope of the outer class and would best be accessed trough a single object. A private method and an inner class don't have the same function. Your methods should be placed in the most appropriate class. – Jeroen Vannevel Aug 27 '13 at 19:00
  • Have you looked at this example? http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html – kosa Aug 27 '13 at 19:02
  • In this case I would just use option 1. It this example don't see the point of option 2. – SamFisher83 Aug 27 '13 at 19:02
  • "group data related to eachother that should only be used in the scope of the outer class and would best be accessed trough a single object" -- The private method also has the scope within the class itself. Isn't it ? What do you actually mean by saying "A private method and an inner class don't have the same function." – user2720864 Aug 27 '13 at 19:03
  • @SamFisher83 when would you like to go for the 2nd one? that what really confuse me – user2720864 Aug 27 '13 at 19:04
  • @user2720864 http://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class – Sajal Dutta Aug 27 '13 at 19:20

1 Answers1

4

For your example, you don't need an inner class. Your first solution is simple, easy-to-read, and sufficient.

An inner class is useful when:

  • You need to implement an interface, but don't want the outer class to implement it.
  • There can be more than one instance of the class.
  • There can be more than one type of the inner class.

EDIT: Examples of each, by request

  • An interface might be implemented by an inner class to implement the Iterator pattern, or a Runnable, ...
  • Multiple instances of an inner class could be necessary to implement an iterator, or a special key type to an internal map, ...
  • Multiple types of inner classes might be necessary for the Strategy pattern, ...
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151