Originally posted by Hima Mangal:
hi all..
pls have a look at the following code..
What will this program print out ?
class Base{
int value = 0;
Base(){
addValue();
}
void addValue(){
value += 10;
}
int getValue(){
return value;
}
}
class Derived extends Base{
Derived(){
addValue();
}
void addValue(){
value += 20;
}
}
public class Test {
public static void main(String[] args){
Base b = new Derived();
System.out.println(b.getValue());
}
}
1. 10
2. 20
3. 30
4. 40
the correct answer is 40.. how is this so.. shouldn't the method in the base class constructor call its own addValue() method??
also, if the methods are declared static, the output is 30.. aren't static methods resolved by the type or reference and not by the type of object??
Thanx in advance..
Now let's walk through the execution of the code and see if that would help answer your question.
1 - In main(),
Derived object is instantiated via 'new' op
2 - This in turn will invoke Derived's constructor
3 - Derived's constructor will
implicitlyinvoke super() (i.e. invoking Base's constructor)
4 - Since Base is top-level class, its field will be intialized next
5 - int value will be assigned with 0
6 - call addValue() in Base's constructor (note: due to overriding - obj is Derived, this method is actually Derived's)
7 - field value goes from 0 to 20 via execution of value += 20
8 - Done with addValue() and back in Base's constructor
8 - Return from Base's constructor back to Derived's constructor
9 - call addValue() in Derived's constructor
10 - field value goes from 20 to 40 via execution of value += 20
11 - Done wirth addValue() and back in Derived's constructor
12 - return to main()
13 - Assign the created object reference to type Base named b
14 - call System.out.println(), which call getValue() first
15 -getValue() returns field value, which was set to be 40
16 - System.out.println() outputs the value fo 40
If both addValue() is declared with static access, then whichever class where addValue() is called, the method belongs to that class unless it is qualified by another name. So at step #6, Base's addValue() is called and the field value will go from 0 to 10 via value += 10; All the remaining execution steps remain and at step #10 field value will go from 10 to 30...
Hope that helps,
- Lam -