Java2all.com  

nested class





Share This Topic -

nested class :

It is possible to define a class within another class; such classes are known as nested classes.

The scope of a nested class is bounded by the scope of its enclosing class.

That means, if class B is defined within class A, then B is known to A, but not outside A.

If A is nesting class B, then A has access to all the members of B, including private members. But the B does not have access to the members of nested class.

There are two types of nested classes:

1.      Static

2.      Non – Static

Static nested class

A static nested class is one which has the static modifier, as it is static it must access the member of its enclosing class through an object.

That means it cannot refer to member of its enclosing class directly.

Non – Static nested class

Non – Static nested class is known as inner class.

It has access to all of its variables and methods of its outer class and can refer to them directly.

An inner class is fully within the scope of its enclosing class.

EX :

class Inner1
{
        class Contents
        {
                private int i = 16;
                public int value()
                {
                        return i;
                }
        }

        class Destination
        {
                private String label;
                Destination(String whereTo)
                {
                        label = whereTo;
                }
        }       
        public void ship(String dest)
        {
                Contents c = new Contents();  // create object of inner class Contents
                Destination d = new Destination(dest);  // create object of inner class Destination

                System.out.println("Shipped " + c.value() + " item(s) to " + dest);
        }

        public static void main(String args[])
        {
                Inner1 p = new Inner1();
                p.ship("Congo");  //call ship method of outer class "inner1"
        }
}

 
Output :
 
Shipped 16 item(s) to Congo
 
Let us see one more example but here the program will not compile
 class Outer 
{
	int outer_x = 100;
	void test() 
	{
		Inner inner = new Inner();
		inner.display();
	}

	// this is an inner class

	class Inner 
	{
		int y = 10; // y is local to Inner
		void display() 
		{
			System.out.println("display: outer_x = " + outer_x);
		}
	}
	void showy() 
	{
		System.out.println(y); // error, y not known here!
	}
}

class InnerClassDemo 
{
	public static void main(String args[]) 
	{
		Outer outer = new Outer();
		outer.test();
	}
}

 
Here, y is declared as an instance variable of Inner. Thus it is not known outside of
that class and it cannot be used by showy( ).