← Java from Scratch Lesson 42 of 88 · 10 XP

Inner classes

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A class can be declared inside another one:

class Outer {
    private int x = 10;

    class Inner {                 // inner: tied to an Outer object, sees its private fields
        int get() { return x; }
    }

    static class Nested {         // static nested: an ordinary class that just "lives" inside Outer
        int answer() { return 42; }
    }

    private static class Secret { }   // private — not visible from the outside at all
}

Outer o = new Outer();
Outer.Inner in = o.new Inner();       // you need an object of the outer class
Outer.Nested n = new Outer.Nested();  // you don't

A typical case is a private static class Node inside your own data structure: nobody outside needs the nodes.

Task. Finish a stack of integers IntStack built on linked nodes: inside it, a private static class Node (a value and a reference to the next node). The methods are push(int), int pop(), int peek(), int size(), boolean isEmpty(). Commands: push N, pop, peek; on an empty stack, pop/peek print empty.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.