Inheritance and class members

Given:

class A { String s = "A"; } class B extends A { String s = "B"; } public class C { public static void main(String[] args){ new C().go();} void go() { A a = new B(); System.out.println(as); } } 

Question:

What is the mechanics of the JVM when running this code? How is it that as is printed as "A".

+4
source share
4 answers

Field references are not subject to polymorphism, therefore, at compile time, a reference to field A is determined because your local variable is of type A.

In other words, the behavior of the field is similar to Java overload behavior on methods, not Java override.

+4
source

You probably expect the fields to be overridden as a method, with dynamic dispatch based on the type of runtime of the object.

This is not how Java works. Fields are not redefined, they are hidden. This means that an object of class B has two fields with the name "s", but access to which of them depends on the context.

Why is this: in fact, it would be useless to redefine the fields, since there is no useful way to make it work when the types are different, and there is simply no sense when the type is the same (as you can just use the superclass field). Personally, I think this is just a compiler error.

+2
source

This is not polymorphism (as noted).

Java has virtual methods , not virtual member variables, i.e. you do not override a property - you hide it.

+1
source

Although member variables inherit from the base class, they are not called polymorphically (for example, dynamic invocation does not apply to member variables).

So, as will refer to the element in the base class, not the derived class.

Having said that, the code does not comply with the principles of OO. Class members must be private / secure (not public or default) depending on the business use case, and you need to provide public methods for getting and setting member values.

0
source

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


All Articles