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

1 comment: