Showing posts with label Local class. Show all posts
Showing posts with label Local class. Show all posts

Monday, November 28, 2011

Access modifiers for Local Class

Tip: Local class declaration can not have any access modifier.

Since local classes are defined within method body, they follow the same modifier rule as any other variable within method.

We will test this by defining a local class and put private access modifier and see if this compiles and runs.
class Furniture {
    public static void print() {
        final int i = 30;
        private class Table { // compilation error here
            void printVar() {System.out.println(i);}
        }
        Table table = new Table();
        table.printVar();
    }
}
Above code defines a class Furniture with one method print (), within print, Table local class is defined and to test today's tip an access modifier is used with class definition.

The code above will get a compilation error where private is defined before local class Table .

Available in Android Market

Sunday, November 20, 2011

Enum as nested class

Tip: Enums can be declared as a top level class, or an inner class, but not within a method.

We can easily test this by defining a class with Enum defined within a method:
class LocalEnum {
 void printCar () {
  enum CarClass { // compilation error here
   COMPACT, MIDSIZE, FULLSIZE;
  }
  System.out.println(CarClass.COMPACT);
  }
}
If you try to compile and run above code snippet you will get error in line enum CarClass.

On the other hand if we take out enum CarClass out of method the definition will be fine.
class LocalEnum {
 enum CarClass {
  COMPACT, MIDSIZE, FULLSIZE;
 }

 static void printCar() {
  System.out.println(CarClass.COMPACT);
 }

 public static void main(String[] args) {
  printCar();
 }
}
We have modified the little bit above so that it could be run easily by putting a main method, printCar is static and enum is defined out of the method. It works ....

Available in Android Market