INNER CLASSES

An inner or nested class is the same as any other class but is declared inside some other class or method. When an instance of an inner class is created, there must normally be a pre-existing instance of the outer class acting as context. An inner class and an outer class belong together; the inner class is not just another member of the outer instance.

Example #1:

class Test {

class Inner {

Inner () {

System.out.println("Hello World");

}

}

public static void main(String args[]) {

Test.Inner i = new Test().new Inner();

}

}

Result:

Hello World

Please note the special syntax used to reference the Inner class from a static context. This is just a shorter approach for this:

Test t = new Test();

Inner i = t.new Inner();

Example #2:

class Test {

String h = "Hello World";

class Inner {

Inner () {

System.out.println(h);

Bye();

}

}

public static void main(String args[]) {

Test.Inner i = new Test().new Inner();

}

void Bye() {

System.out.println("Good bye!");

}

}

Result:

Hello World

Bye

Inner classes have access to all the features of the outer class including also methods.

Access modifiers and Static Inner Classes

Inner classes may be marked with standard access modifiers (private, public, protected) (or default if no modifier is specified). Static inner classes do not have any reference to the enclosing instance. Static methods of inner classes may not access non-static features of the outer class.

Example:

class Test {

private static String h = "Hello World";

static class Inner {

static void MyMethod () {

System.out.println(h);

}

}

public static void main(String args[]) {

Test.Inner.MyMethod();

}

}

Result:

Hello World

The Inner class is an extension of the outer class, so we have access to private members.

Classes defined inside Methods

Anything declared inside a method is not a member of the class but is local to the method. Therefore, classes declared in methods are private to the method and cannot be marked with any access modifier; neither can they be marked as static. However, an object created from an inner class within a method can have some access to the variables of the enclosing method if they declare the final modifier.

Since local variables and method arguments are conventionally destroyed when their method exits, these variables would be invalid for access by inner class methods after the enclosing method exists. By allowing access only to final variables, it becomes possible to copy the values of those variables into the object itself.

Example:

class Test {

public static void main(String args[]) {

Hi("Ernest");

}

static void Hi(String name) {

final String h = "Hello World " + name;

int j = 5;

class Inner {

void MyMethod () {

System.out.println(h);

// j++; // ERROR !!!

}

}

Inner i = new Inner();

i.MyMethod();

}

}

Although the variable name entered the method as normal variable, its contents were added to a final variable.

0 comments:

Post a Comment