Here we go

jabber (jabber)
<本文发表于: 相约加拿大:枫下论坛 >
1) BigEgg2 is the son (subclass) of the Eggs (superclass). BUT, BUT, BUT, BigEgg2 has no idea about "y", because "y" is private in Egg2. Private variables cannot be inherited.

2) The constructor BigEgg2() { insertYolk( new Yolk) )} means

public BigEgg2() {

In any constructor, the first thing is to call super constructor. Since the father is Egg2, super() means Egg2(); Remind::::::: one may
suppress super() in the above but the compiler will add it.

4) Now let's go up to check the definition of Egg2. It has ONE, ONE, and only ONE (private) instance variable called "y". To call Egg2(), JVM needs to first create an Egg2. To create an Egg2, JVM first creates a Yolk named "y". This is done a la Yolk(), so you see the first line : Egg2.Yolk

5) After a Yolk is created, JVM calls Egg2() to do "intialization". As a consequence, you see the second line: New Egg2()

6) Now we come to insertYolk( new Yolk()).
Here we create a Yolk using the defintion in the BigEgg2. Again, the compiler will add a super() to the constructor of Yolk. As a result,
the Yolk constructor is actually

public Yolk(){
Here, super() means Yolk() in the Egg2.
You see, super() prints out the second "Egg2.Yolk()", which is what you tried to understand.

7) At this stage, you have finished executing the very first line in you main(String[] args) method. Congratulations!!!!

8) New let's come to the second as well last line in your main(String[] args) method.
We don't overrride method g(), so we use g() in the Egg2, which is equivalent to y.f(). HOWEVER, HOWEVER, HOWEVER, Method f() has been overridden, so JVM uses the defintion in BigEgg2 and we see last line: BigEgg2.Yolk().f()

9) Summary. To create an instance of a subclass, we always first create one according to the definition in the super class, then we make some modiftions.
If we don't call super in the constructor, the compiler may do that for us. This process can be traced back to java.lang.Object.

10) please pay me one buck because I find I lost one hair for answering your question.
The design of this Egg class is awful. In practice, we should avoid such things. But to learn concepts, Bruce Eckel's book is really good.
<本文发表于: 相约加拿大:枫下论坛 >

2000-12-6 -04:00

回到话题: Jabber,I need your help again,thanks ahead!

回到论坛: HOME枫下论坛枫下论坛主坛工作学习IT杂谈