What happens if you create an inner class and then inherit from the encapsulated class and redefine the inner class? In other words, is it possible for us to overwrite an inner class? This may seem like a very useful concept, but "overwrite" an inner class--as if it were another method of an external class--the concept does not actually do anything:
: Bigegg.java
//An inner class cannot is overriden
//Like a method
class Egg {
protected class Yolk { C6/>public yolk () {
System.out.println ("Egg.yolk ()");
}
private yolk y;
Public Egg () {
System.out.println ("New Egg ()");
y = new yolk ();
}
}
public class Bigegg extends Egg {public
class yolk {public
yolk () {
System.out.println ("Bigegg.yolk ()") ;
}
}
public static void Main (string[] args) {
new Bigegg ();
}
}///:~
The default builder is synthesized automatically by the compiler, and the default builder of the underlying class is invoked. You might think that because you're ready to create a Bigegg, you'll use yolk's "overwritten" version. But that is not the case. The output is as follows:
New Egg ()
Egg.yolk ()
This example simply reveals that when we inherit from an external class, there is no additional inner class to go on. However, it is still possible to "explicitly" Inherit from the inner class:
//: Bigegg2.java//Proper Inheritance of a inner class class Egg2 {protected class yolk {p
Ublic yolk () {System.out.println ("egg2.yolk ()");
public void F () {System.out.println ("Egg2.yolk.f ()");
} private yolk y = new yolk ();
Public Egg2 () {System.out.println ("New Egg2 ()");
} public void Insertyolk (yolk yy) {y = yy;}
public void G () {y.f ();}} public class BigEgg2 extends Egg2 {public class yolk extends Egg2.yolk {public yolk () {System.out.println ()
Bigegg2.yolk () ");
public void F () {System.out.println ("Bigegg2.yolk.f ()");
} public BigEgg2 () {insertyolk () (New yolk ());}
public static void Main (string[] args) {Egg2 e2 = new BigEgg2 ();
E2.G (); }
} ///:~
Now, Bigegg2.yolk explicitly expands the egg2.yolk and overrides its approach. Method Insertyolk () allows BIGEGG2 to trace one of its own yolk objects to the Egg2 y handle. So when G () calls Y.F (), it is overwritten with F (). The output results are as follows:
Egg2.yolk ()
New Egg2 ()
Egg2.yolk ()
Bigegg2.yolk ()
Bigegg2.yolk.f ()
The second call to Egg2.yolk () is the base class builder call to the Bigegg2.yolk Builder. Call
g () can be found using the overwritten version of F ().