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)
text
fields in theClassA
andClassB
classes does not change. Where what happened in the first case, it remained there in the second. The difference is whichtext
field (ClassA
orClassB
) you refer to. - Actually, because of such "misunderstandings", it is necessary to avoid inheritance whenever possible. - avp