Ich versuche, auf die Variable der Kindklasse durch die Methode der Eltern zuzugreifen, die this
Schlüsselwort innerhalb der Methode verwendet. aber es druckt nicht den Wert des Kindes, wenn die Methode von Childs Objekt aufgerufen wurde. Stattdessen gibt es den Wert der Elternklasse aus, selbst wenn diese Methode von einem Kindobjekt aufgerufen wurde.'this' Das Schlüsselwort greift nicht auf die beabsichtigte Variable zu. Warum?
Hier ist mein Code:
class C {
int t = 9;
void disp() {
// here 'this' shows to which object its referring.
// It showed me same as System.out.println(b) showed me
System.out.println(this);
/*
But, why this.t is printing 9,
when this method is called by 'b' reference variable,
it should print 0, because B class contains instance variable t
of its own and here this is pointing to the object of B class,
it shows 9 for 'c' and 1 for 'c1' but y not similarly 0 for 'b'
as when the method is called by 'b',
***this refers to the memory location of b but doesn't prints the value of that object***,
hows that going on???
*/
System.out.println(this.t);
}
}
class B extends C {
int t = 0;
}
class A {
public static void main(String args[]) {
C c = new C();
C c1 = new C();
B b = new B();
c1.t = 1;
System.out.println("Memory location of c-->" + c);
c.disp(); // here output is 9
c1.disp(); //here output is 1
System.out.println("Memory location of b-->" + b);
b.disp();
}
}
Ausgang:
c-->[email protected]
[email protected]
9
[email protected]
1
b-->[email protected]
[email protected]
9
Sie können Felder nicht überschreiben, sondern nur ausblenden. Das heißt, jeder Code im übergeordneten Element, der ein Feld betrachtet, greift immer auf das Feld des übergeordneten Elements und nicht auf das Feld des untergeordneten Elements zu. – RealSkeptic
Hinweis: Sie möchten, dass wir unsere Zeit nutzen, um Ihnen zu helfen. Also machst du das so einfach wie möglich; Beginnen Sie mit der Verwendung der "Vorschau" -Funktion, um sicherzustellen, dass Ihr Quellcode anständig und lesbar formatiert ist. Außerdem; Ich verstehe deine Frage wirklich nicht. – GhostCat