When defining an internal class, this internal class hasImplicit reference(Implicit reference) Points to the instance of the external class. For example, the following code:
class WithInner { class Inner {}}
Actually, internal class
Inner
By default, there is a constructor with parameters. Let's take a look at it through reflection.
import java.lang.reflect.Constructor;import java.lang.reflect.Field;class WithInner { class Inner { public void getConstructors() { for (Constructor<?> cons : getClass().getDeclaredConstructors()) { StringBuilder sb = new StringBuilder(); sb.append("constructor: ").append(cons.getName()).append("("); for (Class<?> param : cons.getParameterTypes()) { sb.append(param.getSimpleName()).append(", "); } if (sb.charAt(sb.length() - 1) == ‘ ‘) { sb.replace(sb.length() - 2, sb.length(), ")"); } else { sb.append(‘)‘); } System.out.println(sb); } } }}public class InheritInner { public static void main(String[] args) { WithInner wi = new WithInner(); WithInner.Inner i = wi.new Inner(); i.getConstructors(); }}
Output result:
constructor: WithInner$Inner(WithInner)
The result shows that the parameter type is an external class (
Outer class), That is, when constructing an internal class, it must be referenced by an external class. Next let's
InheritInner
Inheritance
WithInner.Inner
.
class WithInner { class Inner {}}public class InheritInner extends WithInner.Inner { public static void main(String[] args) { }}
Compilation fails:
InheritInner.java:5: an enclosing instance that contains WithInner.Inner is requiredpublic class InheritInner extends WithInner.Inner { ^1 error
The error message prompts usInheritInner
OneWithInner
Instance.
Let's giveInheritInner
Add the constructor with parameters that we reflect. The compilation fails, and the same error will be reported. This is because the syntax stipulates that, when inheriting internal classes, you must addenclosingClassReference.super()
.
class WithInner { class Inner {}}public class InheritInner extends WithInner.Inner { public InheritInner(WithInner wi) { wi.super(); } public static void main(String[] args) { WithInner wi = new WithInner(); InheritInner ii = new InheritInner(wi); }}
OK, compilation passed, and running is normal. But I am not very clear about why I want to do this.
References
Written with stackedit.
How to inherit an internal class