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 extends Arc2D. (c.f. http://download.oracle.com/javase/6/docs/api/java/awt/geom/Arc2D.Float.html)
Also, sun.org.mozilla.javascript.internal.FunctionNode.Jump extends sun.org.mozilla.javascript.internal.Node, which is a superclass of FunctionNode. (sorry... cannot find a link to the javadoc)
To me, this seems odd. Could you then create these?
new Arc2D.Float.Float() //n.b. I couldn't get this to compile in Intellij IDEA;
new FunctionNode.Jump.Jump.Jump(1); // I could get this to compile
What purpose does it serve to have a subclass nested as an inner class of the superclass?
I wondered whether it was to access something in the superclass, but if you wanted to access any variables/methods in the parent, you could use
super.variable;
or
super.method();
Edit 1: jjnguy has suggested it's to keep the logic in the same place. In which case, why wouldn't you write a file com.mypackage.AbstractTest:
abstract class AbstractTest {
abstract String getString();
}
class ExtensionTest extends AbstractTest {
@Override
String getString() {
return "hello world";
}
}
... rather than:
abstract class AbstractTest {
abstract String getString();
class ExtensionTest extends AbstractTest {
@Override
String getString() {
return "hello world";
}
}
}
Edit 2: It has rightly been pointed out that the suggestion in my previous edit was flawed, as couldn't construct ExtensionTest outside of the package. However, I've had a further think about this over the weekend, so what about the following:
abstract class Test {
public class ExtensionTest extends AbstractTest {
@Override
String getString() {
return "hello world";
}
}
private abstract class AbstractTest {
abstract String getString();
}
}
In essence, the best answer I've seen so far is that having an inner class extend its outer class allows the logic to be grouped together. However, I think that this can be done without the extension.
In my mind, it seems like bad design to have a class that can have an infinite number of the same subclasses nested within it. (Context: this came up whilst trying to produce a dictionary for a code completion utility, and threw a StackOverflowException. I found a workaround, but I just cannot understand why it had been designed that way.)
javac
will happily compile the lineObject obj3 = new java.awt.geom.Arc2D.Float.Float.Float ();
. – Tymon