A class inside a class
If a small class is only useful together with one other class, you can put it inside that class. A static nested class works just like a normal class, but its name shows where it belongs:
public class Main {
static class Pair {
int a, b;
Pair(int a, int b) { this.a = a; this.b = b; }
int sum() { return a + b; }
}
public static void main(String[] args) {
Pair p = new Pair(3, 4);
System.out.println(p.sum());
}
}Output
7
Inner classes can see their outer object
Without static, it is an inner class. Each inner object belongs to an outer object and can use its fields directly:
class Car {
String model;
Car(String model) { this.model = model; }
class Engine {
void start() {
System.out.println("The engine of the " + model + " goes vroom");
}
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car("Swift");
Car.Engine engine = car.new Engine();
engine.start();
}
}Output
The engine of the Swift goes vroom
Anonymous classes: a class with no name
When you need an object of an interface just once, you can write the class right where you use it:
interface Greeting {
void say(String name);
}
public class Main {
public static void main(String[] args) {
Greeting formal = new Greeting() {
public void say(String name) {
System.out.println("Good evening, " + name + ".");
}
};
formal.say("Dr. Rao");
Greeting casual = name -> System.out.println("Hey " + name + "!");
casual.say("Ravi");
}
}Output
Good evening, Dr. Rao. Hey Ravi!
The second one is a lambda – the modern, shorter way. A lambda only works when the interface has exactly one method; an anonymous class works for any interface or class.