ExamVeda
Login
Home
This question belongs to Java Program Inheritence
Inheritence
?

What will be printed after executing following program code?
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());
	}
}

Answer & Solution
Correct Answer: Option C
When object of new derived is called, the flow goes to Derived() first, by default super(); is present in Derived() as the first statement, so the flow now goes to Base. Here value is initialised to 0 and then addValue() is called. The addValue has been overridden in Derived() hence The Base's addValue() will perform value+20(0+20) .After this control flows back to Derived()'s addValue() where again value+20 is done (20+20). Hence Answer is 40
Examveda
Question posted by Examveda
Community

Join the Discussion

4 Comments
KOTA Ashok
KOTA Ashok 9 years ago
10+20 how 40
KOTA Ashok
KOTA Ashok 9 years ago
Sir I don't know how the output 40 please tell me the answer
Krishna Guru
Krishna Guru 9 years ago
When object of new derived is called, the flow goes to Derived() first, by default super(); is present in Derived() as the first statement, so the flow now goes to Base. Here value is initialised to 0 and then addValue() is called. The addValue has been overridden in Derived() hence The Base's addValue() will perform value+20(0+20) .After this control flows back to Derived()'s addValue() where again value+20 is done (20+20). Hence Answer is 40
Prabha Sekar
Prabha Sekar 9 years ago
i dont know how the output is 40.. please anyone explain that