Monday, 11 January 2016

Java Tutorial : Java inner class example


Click here to watch in Youtube :
https://www.youtube.com/watch?v=CUrueNpS4Mc&list=UUhwKlOVR041tngjerWxVccw

DataStructure.java
public class DataStructure
{

    // Create an array
    private final static int SIZE = 6;
    private int[] arrayOfInts = new int[SIZE];

    public DataStructure()
    {
        // fill the array with ascending integer values
        for (int i = 0; i < SIZE; i++)
        {
            arrayOfInts[i] = i;
        }
    }

    public void printOdd()
    {

        // Print out values of even indices of the array
        DataStructureIterator iterator = this.new OddIterator();
        while (iterator.hasNext())
        {
            System.out.print(iterator.next() + " ");
        }
        System.out.println();
    }

    interface DataStructureIterator extends java.util.Iterator<Integer>
    {
    }

    // Inner class implements the DataStructureIterator interface,
    // which extends the Iterator<Integer> interface
    // we can use inner classes to implement helper classes.

    private class OddIterator implements DataStructureIterator
    {

        // Start stepping through the array from the beginning
        private int nextIndex = 1;

        public boolean hasNext()
        {

            // Check if the current element is the last in the array
            return (nextIndex <= SIZE - 1);
        }

        // Return the odd element.
        public Integer next()
        {
            Integer retValue = Integer.valueOf(arrayOfInts[nextIndex]);
            nextIndex += 2;
            return retValue;
        }
    }

}
InnerClassTest.java
public class InnerClassTest
{

    public static void main(String s[])
    {

        // Fill the array with integer values and print out only
        // values of even indices
        DataStructure ds = new DataStructure();
        ds.printOdd();
    }

}
Output
1 3 5 
Click the below link to download the code:
https://sites.google.com/site/javaee4321/java/NestedClassDemo-InnerExample-App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/NestedClassDemo-InnerExample-App

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/d3069ae3fffccb0c6ba4336662b6a2619d880c61/BasicJava/NestedClassDemo-InnerExample-App/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • No comments:

    Post a Comment

    Google+ Followers

    Google+ Badge