Why we need inner classes in java

Tue, Nov 19, 2019

Read in 2 minutes

Inner classes are defined inside a class.

Why you need inner classes?

Types of inner classes:

innerClassTypes

Non-static Inner class Example:

package explore.innerclass;
import java.util.Iterator;
public class InnerClassDemo {
 private int[] arrayOfInts = {1,2,3,4,5,6,7,8,9};
 //Creating array with values.
public void printEven()
//this method get the array values ,check if it is even and print the even numbers.
{
private class EvenIterator implements Iterator<Object>
    {
        private int nextIndex = 0;
     @Override
     //over riding the  Iterator interface method to check if the next the value is available
        public boolean hasNext() {
        return (nextIndex <= arrayOfInts.length - 1);
                }
            @Override
        public Integer next() {
        //Get the array value by the index
      Integer arrayValue = Integer.valueOf(arrayOfInts[nextIndex]);
        nextIndex =nextIndex+1;	 //increasing the index value by one.
    return arrayValue;
         }
    }
 public static void main(String args[]) {
      InnerClassDemo ds =new InnerClassDemo();
    ds.printEven();
     }

Points to be Remembered :