There are some cases in Java where an inner class extends an outer class.
For example, java.awt.geom.Arc2D.Float is an inner class of java.awt.geom.Arc2D, and also exten
There are two cases of inner-classes:
static inner-classes. The inner-class does not keep reference to the outer-class.
non-static inner-classes. The inner-class does keep a reference to the outer-class.
The case of a static inner-class that extends the outer-class is not as interesting as the non-static inner-class extending the outer-class.
What happens with the latter is: to create the inner-class, one needs a reference to the outer-class. However, as the inner-class is an instance of the outer-class, it also accepts a reference to another instance of the inner-class, to be used as outer-class.
Let's look at some code:
Outer a = new Outer();
Outer.Inner b = a.new Inner();
// Only possible when Inner extends Outer:
Outer.Inner c = a.new Inner().new Inner();
If you know the builder pattern, this can be used to have an OOP-version of it:
public abstract class Command {
// Not possible to create the command, else than from this file!
private Command() {
}
public abstract void perform();
public static class StartComputer extends Command {
public void perform() {
System.out.println("Starting Computer");
}
}
public class OpenNotepad extends Command {
public void perform() {
Command.this.perform();
System.out.println("Opening Notepad");
}
}
public class ShutdownComputer extends Command {
public void perform() {
Command.this.perform();
System.out.println("Shutting Computer");
}
}
}
Which is used as: new Command.StartComputer().new OpenNotepad().new ShutdownComputer().perform();
.