Good all weekend! Unlike Socrates, I realized that I really did not know anything. I took a Java basics test and shuddered when I got the result. Interested one question. Actually the simplest code with hierarchy:

class ClassA{ public String text = "from A"; public void setText( String text ) { this.text = text; } public String getText() { return text; } } class ClassB extends ClassA{ public String text = "from B"; public void setText( String text ) { this.text = text; } public String getText() { return text; } } 

Somewhere in the “wilds” public static void:

 ClassB classB = new ClassB(); ClassA classA = classB; // (4) //classA.setText( "from A" ); // (2) classA.text = "from A"; // (3) // вывод System.out.println( "classA.text:\t" + classA.text ); // (1) System.out.println( "classB.text:\t" + classB.text ); System.out.println( "getTextA:\t" + classA.getText() ); System.out.println( "getTextB:\t" + classB.getText() ); 

Actually the conclusion is obvious - everywhere, except for the line (1), a "tram-pam-pam: from B" will be issued. But if you comment out (2) and comment out (3), then EVERYWHERE in the output will be "tram-pam-pam: from A". So the question is: where, in the first case, will the “text” field of the “classA” object containing the value “from A” be located in memory? What happens after the execution of line (4)? If possible, please answer in more detail)

  • one
    Recently, the same substantive issue was discussed: hashcode.ru/questions/266434 - VladD 1:46
  • one
    @nightin_gale: you don't want to know that. As far as I understand, this is not defined by the standard, which means that each compiler has the right to implement it in its own way. It is enough to know the meaning of a virtual call — the difference between compile-time and runtime-binding. - VladD
  • one
    good)) I don’t want to) thanks) - nightin_gale
  • one
    @nightin_gale, the memory location of the text fields in the ClassA and ClassB classes does not change. Where what happened in the first case, it remained there in the second. The difference is which text field ( ClassA or ClassB ) you refer to. - Actually, because of such "misunderstandings", it is necessary to avoid inheritance whenever possible. - avp
  • one
    Advice "to avoid inheritance" is a great folly and it seems to be a heavy legacy of pure S - Andrew Frolov

1 answer 1

According to the link above, everything was correctly said. Here is a description of this behavior in the standard.

Field Access Using a Primary