Java Anonymous inner class.

Anonymous inner class.

  • Is a class, which have no name and the class implementation is combined with an object instantiation of the class.
  • Can be performed through implementing an interface or here as extending a class.
    Anonymous inner class example:
    public class AnonymousCar {   
      String _color;
      AnonymousCar(String col){
        _color=col;
      }
      Object obj = new Object() {          //  Anonymous inner class
        public String toString() {
          return "My color is "+_color+"!";
        }
      };
    
    
      public static void main(String[] args) {
        AnonymousCar myCar= new AnonymousCar("blue") ;      
        // instantiated object of class Anonymouscar
        System.out.println(myCar.obj);
      }
    }
    
    
    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.