Inner Class Example in Java

By: Tamil Selvan Emailed: 1768 times Printed: 2515 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

To see an inner class in use, consider a simple stack of integers. Stacks, which are a common data structure in programming, are well-named— they are like a "stack" of dishes. When you add a dish to the stack, you put it on top; when you remove one, you remove it from the top. The acronym for this is LIFO (last in, first out). Dishes on the bottom of the stack may stay there quite a long time while the upper dishes come and go.

The StackOfInts class below is implemented as an array. When you add an integer (called "pushing"), it goes into the first available empty element. When you remove an integer (called "popping"), you remove the last integer in the array.

The StackOfInts class below (an application) consists of:

  • The StackOfInts outer class, which includes methods to push an integer onto the stack, pop an integer off the stack, and test to see if the stack is empty.
  • The StepThrough inner class, which is similar to a standard Java iterator. Iterators are used to step through a data structure and typically have methods to test for the last element, retrieve the current element, and move to the next element.
  • A main method that instantiates a StackOfInts array (stackOne) and fills it with integers (0, 2, 4, etc.), then instantiates a StepThrough object (iterator) and uses it to print out the contents of stackOne.

public class StackOfInts {
	private int[] stack;
	private int next = 0;  // index of last item in stack + 1
	public StackOfInts(int size) {
		//create an array large enough to hold the stack
		stack = new int[size];
	public void push(int on) {
		if (next < stack.length)
		   stack[next++] = on;
	public boolean isEmpty() {
		return (next == 0);
	public int pop(){
		if (!isEmpty()) 
		   return stack[--next]; // top item on stack
		   return 0;
	public int getStackSize() {
		return next;
	private class StepThrough { 		
		// start stepping through at i=0
		private int i = 0; 
		// increment index
		public void increment() {
			if ( i < stack.length)
		// retrieve current element
		public int current() {
			return stack[i];
		// last element on stack?
		public boolean isLast(){
			if (i == getStackSize() - 1)
			   return true;
			   return false;
	public StepThrough stepThrough() {
		return new StepThrough();
	public static void main(String[] args) {
		// instantiate outer class as "stackOne"
		StackOfInts stackOne = new StackOfInts(15);
		// populate stackOne
		for (int j = 0 ; j < 15 ; j++) {
		// instantiate inner class as "iterator"
		StepThrough iterator = stackOne.stepThrough();
		// print out stackOne[i], one per line
		while(!iterator.isLast()) {
			System.out.print(iterator.current() + " ");

The output is:

0 2 4 6 8 10 12 14 16 18 20 22 24 26 

Note that the StepThrough class refers directly to the stack instance variable of StackOfInts.

Inner classes are used primarily to implement helper classes like the one shown in this example. If you plan on handling user-interface events, you'll need to know about using inner classes because the event-handling mechanism makes extensive use of them.

Local and Anonymous Inner Classes

There are two additional types of inner classes. You can declare an inner class within the body of a method. Such a class is known as a local inner class. You can also declare an inner class within the body of a method without naming it. These classes are known as anonymous inner classes. You will encounter such classes in advanced Java programming.


You can use the same modifiers for inner classes that you use for other members of the outer class. For example, you can use the access specifiers - private, public, and protected - to restrict access to inner classes, just as you do to other class members.

Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.

Bookmark and Share


1. View Comment

Very Useful example, Thanks

View Tutorial          By: Prabhat Kumar Singh at 2011-12-21 20:44:00
2. View Comment

here is one more inner class example
public class Account {
protected static int accNo=1000025475;
protected String accHolderName;
protected double bal;
public Account()
public Account(String accHolderName, double bal)
this.accHolderName = accHolderName;
this.bal = bal;
public String toString() {
return "accNo="+accNo+"\naccHolderName=" + accHolderName + ", \nbal=" + bal
public static class Locker
int lockerId=2542;

public Locker()

public String toString() {
return "LockerId="+lockerId;

public static void main(String[] args){

Locker l1=new Locker();
Account a2=new Account("saleem",5125.24);
Locker l2=new Locker();
Account a3=new Account("arif",15847);

View Tutorial          By: shahalam shaikh at 2012-02-13 21:08:30

Your name (required):

Your email(required, will not be shown to the public):

Your sites URL (optional):

Your comments:

More Tutorials by Tamil Selvan
Inner Class Example in Java
PreparedStatement Example in Java
UNIX read and write system calls sample program in C
Pointer Arrays and Pointers to Pointers in C
Relational and Logical Operators in C
Arithmetic Operators in C
strlen() sample program in C++
Sample program to draw a arc in J2ME
What Java Has Removed from C++
FileReader and FileWriter example program in Java

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
InetAddress Example program in Java
Read from a COM port using Java program
Stack example in Java - push(), pop(), empty(), search()
How to use ArrayList in Java
The Basic Structure of a Simple Java program
Using StringTokenizer in Java
FileReader and FileWriter example program in Java
Transient vs Volatile modifiers in Java
Vector example in Java
Method Overriding in Java
Method Overloading (function overloading) in Java
instanceof sample program in Java
append() in Java
Student marks calculation program in Java
Reading from a file and writing to a file using Java program
Most Emailed Articles (in Java)
Text to Speech conversion program in Java
inheritance in Java
How to initialize an Array and how to copy the array
Using Charts in JasperReports
What is Unicode?
Operator Precedence in Java
Of Object, equals (), == and hashCode ()
DateFormat sample program in Java
A Simple whois program in Java
PushbackReader sample program in Java
CharArrayReader example program in Java
ByteArrayOutputStream - sample program in Java
Vector example in Java
Arrays example in Java - asList(), binarySearch(), fill(), sort(), equals()
HashSet Sample program in Java