Introduction to Nested Class

Introduction to Nested Class


Posted in : Core Java Posted on : October 7, 2010 at 3:56 PM Comments : [ 0 ]

This section contains the description about Nested Class in java

Introduction to Nested Class

The Nested classes are classes which are defined within another class. A nested class has access to the members including private members of the class in which it is reside. But the enclosing class does not have access to the members of the nested class. 

Nested classes are of two types :

1. Static

2. Non-static

Static nested class : The nested class which is defined with 'static' modifier is known as 'static nested class'. Static nested class can access the member of it's enclosing class through an object. It can't access these member directly.

Non-Static nested class : The non-static nested class or  inner class  has access to all the members of it's enclosing class or outer class directly in the same way that other non-static member of outer class do.

Example : Simple inner class


class Outer {
	int x = 100;

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

	// Inner Class
	class Inner {
		void display() {
			System.out.println("display : x = " + x);
		}
	}

}

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

}

Output :

C:\Program Files\Java\jdk1.6.0_18\bin>javac SimpleInnerClass .java

C:\Program Files\Java\jdk1.6.0_18\bin>java SimpleInnerClass
display : x = 100

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics