Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why java does not support dynamic variable dispatch [closed]

Please excuse me if title is wrong. There are two class Test and TestChild1 where TestChild1 is inherited from Test. Both classes have a variable named "a". When I tried to access variable "a" through superclass variable which is instantiated with subclass object, it is giving the value that is initialized with in superclass not subclass. following is the code that raised the doubt

class Test {
    public int a = 10;
}

class TestChild1 extends Test {
    public int a = 20;
}

class Main {
    public static void main(String args[]) {
        Test test = new TestChild1();
        System.out.println(test.a); // results in 10
    }
}

Please give me the reasons for this behavior. Thanks in advance....

like image 760
syam Avatar asked Dec 16 '22 08:12

syam


2 Answers

Because the Java designers decided to make methods polymorphic (and thus overridable), but not fields.

When you reference a field from an object, the compiler decides which field to use, based on the declared type of the variable, which, in this case, is Test.

When you refer to methods, the JVM, at runtime, chooses which method to call based on the actual, concrete type of the object which, in this case, is TestChild.

OO is all about encapsulation of state, so you should almost never expose fields to the outside anyway.

like image 93
JB Nizet Avatar answered Jan 12 '23 00:01

JB Nizet


The class TestChild1 has two variables with the same name. If you access them through Test you get the first one, from TestChild1 you get the second one.

To get your expected result, you should not declare a in the derived class. Instead you should initialize it in the costructor of the derived class.

like image 41
Emanuele Paolini Avatar answered Jan 12 '23 00:01

Emanuele Paolini