简体   繁体   中英

Private method or inner class, which one to use

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.

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, ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM