Friday, January 22, 2016

Topic 20: Nested and Inner Classes

  • A class can be defined within another class and are known as nested classes

  • The scope of a nested class is its enclosing class. Thus, if class B is defined within class A, then B does not exist independently of A. 

  • A nested class has access to the members, including private members, of the class in which it is nested. However, the enclosing class does not have access to the members of the nested class. 

  • A nested class declared directly within a enclosing class scope, is a member of its enclosing class. 

  • It is possible to declare a nested class that is local to a block. 

  • Nested classes are particularly helpful when handling events.

  • There are two types of nested classes: static and non-static.

  • A static nested class has static modifier applied. It must access the members of its enclosing class through an object. Because of this restriction, static nested classes are seldom used.

  • An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do.

The following code fragment illustrates how to define and use an inner class.

// Demonstrate an inner class.
class Outer
{
int outer_x = 100;

void test()
{
Inner inner = new Inner();
inner.display();

}

// this is an inner class
class Inner
{
void display()
{
System.out.println("display: outer_x = " + outer_x);
}
}

}

//Inside other class containing main()
Outer outer = new Outer();
outer.test();

//To access non-static Inner class outside Outer class definition
Outer.Inner inner = outer.new Inner();


//To access static Inner class outside Outer class definition
//Inner inner = outer.Inner();


inner.display();

 

An instance of Inner can be created only within the scope of class Outer. The Java compiler generates an error message if any code outside of class Outer attempts to instantiate class Inner. (In general, an inner class instance must be created by an enclosing scope.) We can, however, create an instance of Inner outside of Outer by qualifying its name with Outer, as in Outer.Inner.


It is possible to define inner classes within any block scope. For ex, we can define a nested class within the block defined by a method or even within the body of a for loop, as shown:

for(int i=0; i<10; i++)
{
class Inner
{
void display()
{
System.out.println("display: outer_x = " + outer_x);
}
}
Inner inner = new Inner();
inner.display();

 

Click for NEXT article.

 

Please feel free to correct me by commenting your suggestions and feedback.

 

No comments:

Post a Comment