my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overriding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overriding" Watch "Overriding" New topic


sandhi mridul
Ranch Hand

Joined: Jan 25, 2008
Posts: 71

Output= 20

What is going on in this method?
Plaese help me.

Daniel Chemko
Ranch Hand

Joined: Feb 27, 2008
Posts: 32
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

Joined: Feb 23, 2008
Posts: 8
please can anyone explain me the control 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 is the control flowing..?? :roll:
Bednarski Adam

Joined: Mar 21, 2007
Posts: 13
I've changed output methods, look at code:

as results you will get:

D:addValue -> 20
D:addValue -> 40
Test:main -> 40

So only explanation is that because you are using object "Derived" ( Derived()...) then in Base() constructror you are using overriden method from "Derived".

Please correct me if I'm wrong !

Joined: Mar 01, 2008
Posts: 1
* To change this template, choose Tools | Templates
* and open the template in the editor.

package javaapplication4;

* @author michal
import java.util.*;

class Base{
int value = 0; // local variable is unique


void addValue(){
value += 10;
int getValue(){
return value;
class Derived extends Base{
int value = 3; // local variable is unique


void addValue(){ // <<<<<======== US Method
value += 20;
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
Thanks .... It helped.
Dean Jones
Ranch Hand

Joined: Dec 29, 2007
Posts: 129
The code given by Mlody is realy interesting, gives "0" on invocation of getValue() method.
I agree. Here's the link:
subject: Overriding
Similar Threads
initialisation & control flow
What will this program print out? Why?
oo concepts
confusion in the output
polymorphism Problem (tricky)