Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes Dynamic dispatch Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Dynamic dispatch" Watch "Dynamic dispatch" New topic

Dynamic dispatch

Prem Krishnan

Joined: Jun 26, 2008
Posts: 7

Please go through the following piece of code

<pre name="code" class="core">class SubTest extends Test {

public int aNumber;
public SubTest() {
aNumber = 17;
public void doubleANumber() {
System.out.println("Inside SubTest.doubleANumber()");
aNumber *= 2;

public class Test {
public int aNumber;
public Test() {
aNumber = 6;
public void doubleANumber() {
System.out.println("Inside Test.doubleANumber()");
aNumber *= 2;

public static void main(String[] args) {
Test t = new SubTest();
System.out.println(”The value of aNumber is ” + t.aNumber);

The result of this code is
Inside SubTest.doubleANumber()
The value of aNumber is 6

Since the object is refering to an instance of the subclass SubTest, I understood how it prints "Inside SubTest.doubleANumber()", what I am confused is
(1) why it is not printing "The value of aNumber is 34" insted of "The value of aNumber is 6" ?
(2) why it is taking the variable 'aNumber' in the superclass (here: Test) without considering 'aNumber' in the subclass (here:subTest).

[edit]Add code tags. CR[/edit]
[ July 17, 2008: Message edited by: Campbell Ritchie ]
Rob Spoor

Joined: Oct 27, 2005
Posts: 20269

Unlike methods, fields are NOT overridden nor does polymorphism apply to them. Instead, SubTest.aNumber shadows Test.aNumber. So what happens is this:

- SubTest() is called
- Test() is called, and Test.aNumber is set to 6
- SubTest.aNumber is set to 17
- SubTest.doubleNumber is called. Because of the shadowing, this multiplies SubTest.aNumber by 2, making it 34
- Test.aNumber is recalled in the main method. It's still 6.

Because you are using a reference of type Test, it will use Test.aNumber. If you change the declaration to SubTest t it will print 34.

How To Ask Questions How To Answer Questions
Sachin Adat
Ranch Hand

Joined: Sep 03, 2007
Posts: 213
Nice explanation Rob..........

Even I was a bit confused, Now its clear........

How To Ask Questions On Java Ranch - How To Answer Questions On Java Ranch
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46320
Please, Prem Krishnan, Use Code Tags, using the code button under the message window. I have added them so you can see how much easier the code is to read.
Prem Krishnan

Joined: Jun 26, 2008
Posts: 7
Rob thank you very much for that wonderful explanation.
Ritchie, I will use the code tags from now own, Thank you.
I agree. Here's the link:
subject: Dynamic dispatch
It's not a secret anymore!