Inner, Nested and Anonymous Classes
A class can live inside another class. Static nested classes need no outer instance, inner classes do, and anonymous classes implement an interface inline.
Example
public class Main {
interface Greeter { String greet(String n); }
static class Box { int v = 5; }
class Inner { String hi() { return "inner of Main"; } }
public static void main(String[] args) {
Greeter g = new Greeter() { public String greet(String n) { return "Hi " + n; } };
System.out.println(g.greet("Ada") + " " + new Box().v);
System.out.println(new Main().new Inner().hi());
}
}Result
Hi Ada 5 inner of Main
Exercise
Name this kind of class: new Greeter() { } is an ___ class.
new Greeter() { } is an class
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.