Local Class

LOCAL CLASS: 


  • Local Class is a class that are defined in blocks which is group of zero or more statements between balanced braces. You typically find Local Classes in the body of the method. But don't confuse this with Nested class, because you can't declare Nested Class in method/loop/condition.
  • Local Classes are non static because they have access to instance member of Enclosing(Outer) block like inner(non-static) nested class have access to all the members of the Outer Class.
  • Local class in static methods can only refer to the static members of the Enclosing(Outer) class. For Example: In Below Code, if we declare greetingsInEnglish() method as a static then we can't access String "name" in that method. But if we declare String "name" as a static the we can access in static method.
  • So we conclude that we can access all static members of Outer Class in static method. 
  • But In Reverse We can access all the static members in non-static method/code.
  • You can not define Interface inside any block. You can only declare it in Enclosing(outer) Class, because Interface are inherently static.
public class LocalClass 
{
public String name="Urvish";
interface HelloThere
{
public void greet();
}
public void greetingsInEnglish()
{
class EnglishHelloThere implements HelloThere
{
public void greet() 
{
  System.out.println("Hello "+name);
}
}
EnglishHelloThere myGreetings = new EnglishHelloThere();
myGreetings.greet();
}
public static void main(String args[])
{
LocalClass cls = new LocalClass();
cls.greetingsInEnglish();
}
}


  • You can't declare static initializer or member interface in a Local Class. The following code doesn't compile because EnglishHelloThere.greet(); is declared static.
   
   public void greetingsInEnglish() 
   {
        class EnglishHelloThere  // Local Class
        {
            public static void greet()  // static method
            {
                System.out.println("Bye bye");
            }
        }
        EnglishHelloThere.greet();
   }


  • The compiler generates an error similar to "modifier 'static' is only allowed in constant variable declaration", Which means that static member can be allowed in Local Class if they are declared final.
  • Constant Variable is a variable of primitive type or type string that is declared final and initialized with compile-time constant expression(string or arithmetic expression that can be evaluated at compile time).
  • Following code execute static member in Local class

 public void greetingsInEnglish() 
   {
        class EnglishHelloThere  // Local Class
        {   
            public static final String farewell = "Bye bye";
            public static void greet()  // static method
            {
                System.out.println("farewell);
            }
        }
        EnglishHelloThere myEnglishHello = new EnglishHelloThere();
        myEnglishHello.greet();
   }

Comments