Java Local Inner Class

Java Local Inner Class.

  • A local inner class is defined inside a block of code inside a containing class, and only visible within that block.
  • It can be defined in methods inside static initializers, non-static initializers, and constructors. .
  • At declaration it cannot use any access modifiers such as public, private, or protected, as its scope is always limited to its enclosing block.
    Local inner class example:
    public class LocalCar {
      String _color;                       // object of inner class country
     LocalCar(String col){
        _color=col;
      }
      public String getColor() {
        class color {                      // Local inner class
          String showColor() {
            return "My color is "+_color+"!";
          }
        }
        color _color=new color();          // instantiate the inner class
        return _color.showColor();
      }
    
      public static void main(String[] args) {
        LocalCar myCar= new LocalCar("blue"); // instantiated object of class LocalCar
        System.out.println(myCar.getColor());
      }
    }
    
    The result of this is:
    My color is blue!
    You can download this example here (needed tools can be found in the right menu on this page).
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.