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());
}
}
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());
}
}
A. 30
B. 10
C. 40
D. 20
E. None of these
Answer: Option C
Solution(By Examveda Team)
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 40Join The Discussion
Comments ( 4 )
A. The process of acquiring properties and behaviors of one class by another
B. The process of creating objects
C. The process of encapsulation
D. The process of overloading methods
In Java, which keyword is used to implement inheritance between classes?
A. inheritsFrom
B. inherits
C. implements
D. extends
A. The class that inherits properties and behaviors
B. The child class
C. The class that is inherited from
D. The class that is marked as "final"
In Java, can a subclass inherit constructors from its superclass?
A. Only if the subclass is marked as "final"
B. Yes, a subclass inherits constructors from its superclass
C. Only if the superclass is marked as "static"
D. Only if the subclass is marked as "final"
10+20 how 40
Sir I don't know how the output 40 please tell me the answer
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
i dont know how the output is 40.. please anyone explain that