Inheritance of inner classes
Inheriting anonymous inner classes in Java one of the things that ends up is that the constructor of the inner class must point to a reference to its perimeter object, so take a special syntax. The sample code given in the book can have a compiled version, and Enclosingclassreference.super () must be added within the constructor of the inherited inner class.
1 classwithinner{2 classinner{}3 }4 Public classInheritinnerextendswithinner.inner{5 Inheritinner () {6Enclosingclassreference.Super();7 }8 Inheritinner (Withinner wi) {9Wi.Super();Ten } One Public Static voidMain (string[] args) { AWithinner WI =NewWithinner (); -Inheritinner I1 =NewInheritinner (WI); - } the}
Overrides for inner classes
In Java, you can override a method of a parent class without requiring a particular declaration, but if you want to overwrite the inner class of the parent class, you must indicate who is overriding it.
code Block 1 and code block 2 illustrate this point
class egg{ private yolk y; protected class yolk{ public yolk () { System.out.println ( "egg.yolk" public Egg () {System.out.println ( New Egg () "); Y =new yolk (); }}
Public class extends egg{ publicclass yolk { public yolk () { System.out.println ("Bigegg.yolk ()"); } } Public Static void Main (string[] args) { // TODO auto-generated method stub new Bigegg (); }}
The output of the code block is: New Egg (), Egg.yolk ()
If you want to overwrite the book, the following example is given:
1 Public classEGG2 {2 protected classYolk {3 Publicyolk () {4System.out.println ("Egg2.yolk ()");5 }6 7 Public voidf () {8System.out.println ("Egg2.yolk.f ()");9 }Ten } One A PrivateYolk y =Newyolk (); - - PublicEgg2 () { theSystem.out.println ("New Egg2 ()"); - } - - Public voidinsertyolk (Yolk yy) { +y =yy; - } + A Public voidg () { at y.f (); - } -}
1 Public classBigEgg2extendsEGG2 {2 3 Public classYolkextendsEgg2.yolk {4 Publicyolk () {5System.out.println ("Bigegg2.yolk ()");6 }7 8 Public voidf () {9System.out.println ("Bigegg2.yolk (). F ()");Ten } One A } - - PublicBigEgg2 () { theInsertyolk (Newyolk ()); - } - - Public Static voidMain (string[] args) { + //TODO auto-generated Method Stub -EGG2 e2 =NewBigEgg2 (); + e2.g (); A } at -}
This explicitly overrides the class, when instantiating BigEgg2 (), not only calling the constructor of the parent class, the method of the subclass is also called, E2.G (), the output is no longer the parent class F (), but the subclass.
Think in Java reading notes: Inheritance and overrides of Java anonymous inner classes