Derived class mystery

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sandromani
    New Member
    • Dec 2007
    • 16

    Derived class mystery

    Okay so here is a tricky example from my lecture notes:
    Code:
    class Base {
        private int val;
        Base () {
    	val = lookup();
        }
        public int lookup() { 
    	return 5; 
        }
        public int value() {
    	return val;
        }
    }
    class Derived extends Base {
        private int num=10;
        public int lookup() {
    	return num;
        }
    }
    class Test {
        public static void main( String[] args ) {
    	Derived d = new Derived();
    	System.out.println(d.value());
        }
    }
    I would expect the program to print out 10, but it actually prints out 0... Can anyone explain that?:D
    Code:
    java -version
    java version "1.6.0_18"
    OpenJDK Runtime Environment (IcedTea6 1.8) (fedora-41.b18.fc13-x86_64)
    OpenJDK 64-Bit Server VM (build 14.0-b16, mixed mode)
    Thanks!
  • Oralloy
    Recognized Expert Contributor
    • Jun 2010
    • 988

    #2
    The constructor for Base was executed after the memory was allocated for the object, but before the constructor for Derived was executed .... right?

    So why do you expect that num was set to anything other than a random (or perhaps the default value) when the Base constructor runs?

    Think about it...

    Comment

    • sandromani
      New Member
      • Dec 2007
      • 16

      #3
      Mh right, makes sense... Thanks!

      Comment

      • Oralloy
        Recognized Expert Contributor
        • Jun 2010
        • 988

        #4
        Originally posted by sandromani
        Mh right, makes sense... Thanks!
        You're welcome.

        BTW, I'm not sure what the JVM specification says about such things. That's the ultimate answer, and it probably states that the behaviour is unspecified.

        Comment

        Working...