As you can see from this simple stack dump, both constructors are being called (even if you don't explicitly call super(), its still being called).
Since the Base had its addValue() overwritten, with derived's addValue(), the total is then incremented by 20 each time.
Shahid Ahmed
Greenhorn
Joined: Feb 23, 2008
Posts: 8
posted
0
please can anyone explain me the control flow..in the first program..i.e in the actual question. I dont understand,how the control flows...because,here we have : Base b=new Derived() so,is it that first the Derived() constructor is called? if so,then Derived() constructor has the super() as its first statement, then it should go to Base() constructor..there,we get the value printed '10' but here in the answer,the first one is '20' ...how.??? how is the control flowing..?? :roll:
So only explanation is that because you are using object "Derived" (...new Derived()...) then in Base() constructror you are using overriden method from "Derived".
Please correct me if I'm wrong !
Mlody
Greenhorn
Joined: Mar 01, 2008
Posts: 1
posted
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */
class Base{ int value = 0; // local variable is unique
Base(){ addValue(); }
void addValue(){ value += 10; System.out.println(value); } int getValue(){ return value; } } class Derived extends Base{ int value = 3; // local variable is unique
Derived(){ addValue(); }
void addValue(){ // <<<<<======== US Method value += 20; System.out.println(value); } } public class Main { public static void main(String[] args){ Base b = new Derived(); // Firstly Basic constructor (extends Base), there addValue. But this method is overriden. // Secondly Derived constructor, and addValue +20 System.out.println(b.getValue()); // +20 + 20 = 40 } }
sandhi mridul
Ranch Hand
Joined: Jan 25, 2008
Posts: 71
posted
0
Thanks .... It helped.
Dean Jones
Ranch Hand
Joined: Dec 29, 2007
Posts: 129
posted
0
The code given by Mlody is realy interesting, gives "0" on invocation of getValue() method.