Inner Classes

An inner class is a class declared INSIDE another class. This is done when we want the details of the inner class to only be visible to the class it’s inside. In this case, we declare the inner class private. Here’s the format:

public class OuterClass 
{
    //contents of OuterClass

    private class InnerClass 
    {
        //contents of InnerClass
    }
}

This code should be stored in the file OuterClass.java. No other class (besides OuterClass) knows that InnerClass exists.

For example, suppose we want to store the names and ages of a bunch of people. We can have an inner class called Person, that stores a single person’s name and age. Then, the outer class can have an array of type Person:

public class People 
{
    private int size = 0;
    private Person[] list = new Person[100];

    //Add a new person, if there is room in the array
    public void add(String name, int age) 
    {
        //If there is room left
        if (size < list.length) 
        {
            //Create a new person, and add it to the array
            Person p = new Person(name, age);
            list[size] = p;
            size++;
        }
    }

    //Return the age of the given person
    //Return -1 if the person isn’t in our array
    public int getAge(String name) 
    {
        //loop through all people
        for (int i = 0; i < size; i++) 
        {
            //if this person’s name matches what we’re looking for
            if (list[i].name.equals(name)) 
            {
                //return this person’s age
                return list[i].age;
            }
        }

        //We haven’t returned yet, so we must have not
        //found the name in our array. Return -1.
        return -1;
    }

    //our inner class
    private class Person 
    {
        public String name;
        public int age;

        public Person(String name, int age) 
        {
            this.name = name;
            this.age = age;
        }
    }
}

Here’s how we might use the People class:

People p = new People();
p.add("Fred", 18);
p.add("James", 20);
System.out.println(p.getAge("Fred")); //prints 18

However, we can’t do:

Person pers = new Person("Amy", 26);

from outside the People class, since we can’t see Person outside of People.