This week's book giveaway is in the OCP forum.
We're giving away four copies of OCP Java SE 8 Programmer II Exam Study Guide and have Kathy Sierra, Bert Bates, & Elizabeth Robson on-line!
See this thread for details.
Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Inner Classes  RSS feed

 
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All
Can anybody helpout me in knowing "inner classes" with an example

Regards
-venkat
 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is possible to define a class within another class, such classes are known as Nested Classes, There are two types of nested classes : static and non-static. The most important type of nested class is Inner Class. 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 the other non-static members of the outer class do. Thus, an Inner class is fully within the scope of its enclosing class.

Following program illustrates how to define and use an inner class. The class named Outer has one instance variable named outer_x, one instance method named test(), and defines one Inner class called Inner.


class Outer {
int outer_x = 100;
void test() {
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();
}
}
}

class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}
 
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's an excellent JavaRanch article on inner classes...

http://www.javaranch.com/campfire/StoryInner.jsp
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!