On Wed, 06 Jan 1999 15:13:51 +0000, Richard Jones wrote:

>
>Can someone tell me why this program, when run under
>Linux, prints d = 0 (ie. the variable d isn't being
>initialized as expected)? According to Bruce Eckel's
>book, which is the only reference I have available to
>me, d should be initialized to 1, so I suspect this
>may be a JVM bug ...

Actually, this is where the "how do I run first" problems
happen.

The thing is that until super() is called *and* returns,
the object is not complete - as in storage for it has
not even been allocated, etc.  So, when you have the
constructor in you "SuperClass" calling the method, the
constructors in the "DerivedClass" have not yet had a
chance to run.  They can not run before super() is called
since they need the object to exist before they can store
any data into the object.  Thus, they run after super()
returns.

There are limits to what could be done in the object.
And, there is no way to get around this unless you build
a system that lets each class run before and after each
other class in an object.

>---------------------------------------------------------
>/* SuperClass.java */
>
>public abstract class SuperClass
>{
>  protected SuperClass ()
>  {
>    method ();
>  }
>
>  protected abstract void method ();
>}
>---------------------------------------------------------
>
>---------------------------------------------------------
>/* DerivedClass.java */
>
>public class DerivedClass extends SuperClass
>{
>  public int d = 1;
>
>  public DerivedClass ()
>  {
>    super ();
>  }
>
>  protected void method ()
>  {
>    System.out.println ("d = " + d);
>  }
>
>  public static void main (String[] args)
>  {
>    DerivedClass derivedClass = new DerivedClass ();
>  }
>}
>---------------------------------------------------------
>
>$ java -version
>java version "1.1.6"
>$ java DerivedClass 
>d = 0


Michael Sinz -- Director of Research & Development, NextBus Inc.
mailto:[EMAIL PROTECTED] --------- http://www.nextbus.com
My place on the web ---> http://www.users.fast.net/~michael_sinz

Reply via email to