Tricky example with polymorphism

Example

Can you predict the output of the following code?

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();
        t.doubleANumber();
        System.out.println("The value of aNumber is " + t.aNumber);
    }
}

Result

The output is:
Inside SubTest.doubleANumber()
The value of aNumber is 6

As you see, it was not the reference type but the real object type of t variable that decided which method was invoked at runtime. This way, aNumber of SubTest class was modified. This variable shadowed aNumber of Test class. Therefore, Test.aNumber variable was untouched (didn’t change at all).

0 Responses to “Tricky example with polymorphism”


  • No Comments

Leave a Reply