Java Static Member Class

Java Static Member Class.

  • Is a member class defined within the body of another class and declared static.
  • A static member class is not an inner class, but is considered as a top-level class.
  • It can be declared as public, private, protected, or package-level to restrict its accessibility outside its containing class.
  • You do not need an instance of its enclosing class to create its object as it is static.
  • Static member inner class can access the static members of the class they are contained in.
  • The instantiation of its object can bee done outside and/or inside the containing class.
    Static member inner class example:
    public class StaticCar {
      static String _where="I am a Car from Germany!";
      Country _country;            // object of inner class country
      StaticCar(){
        _country=new Country();    // instantiate the inner class
      }
      static class Country {       // static member inner class
         String showCountry() {
          return _where;
        }
      }
    
      public static void main(String[] args) {
        StaticCar myCar= new StaticCar() ;  // instantiated object of class StaticCar
        System.out.print("Access through an Country reference");
        System.out.println(" created in an object of a StaticCar:");
        System.out.println(myCar._country.showCountry());
        // instantiated object of class StaticCar.Country
        StaticCar.Country country= new StaticCar.Country();
         System.out.println("Access through an Country reference that is local:");
        System.out.println(country.showCountry());
    
      }
    }
    The result of this is:
    Access through an Country reference created in an object of a StaticCar:
    I am from Germany!
    Access through an Country reference that is local:
    I am from Germany!
    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.