Why Java doesn't support dynamic variable submission

Please excuse me if the name is wrong. There are two classes Test and TestChild1, where TestChild1 is inherited from Test. Both classes have a variable named "a". When I tried to access the variable "a" through a superclass variable that is created by an instance of a subclass object, it gives a value that is initialized in the superclass, not the subclass. the following code that raised 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 explain the reasons for this behavior. Thanks in advance.

+4
source share
5 answers

Since the Java developers decided to make the methods polymorphic (and therefore redefinable), but not fields.

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

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

OO is all about encapsulating a state, so you almost never have to open fields outside.

+9
source

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

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

+2
source

You declared your object as Test , not a subclass. At compile time, this means that you are referencing a base class that has 10.

+1
source

Because the behavior is related to methods, not fields.

So, the fields have static binding (in this case, since the test is of type Test , the value of a assigned the value of 10). While methods have dynamic binding.

Since the variable a does not determine the behavior of the Test class, it is assigned a value according to its type, and not as an instance of it.

0
source

JB Nizet has already said everything, but I will add this code for a better understanding:

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

So, if you encapsulate your fields, you would expect behavior.

0
source

Source: https://habr.com/ru/post/1490115/


All Articles