Reputation: 11
I am trying to access child class's variable through parent's method using this
keyword inside method. but its not printing the child's value when the method was called by child's object. Instead it's printing parent class's value even if that method was called by child's object.
Here is my 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();
}
}
Output:
c-->PackageName.C@15db9742
PackageName.C@15db9742
9
PackageName.C@6d06d69c
1
b-->PackageName.B@7852e922
PackageName.B@7852e922
9
Upvotes: 0
Views: 65
Reputation: 3507
You are getting confused between overriding method concept with shadowing of variable, since dynamic binding will call child class method at run time , but this is not true in case of 'this' reference of variable it will not overwrite parent variable even if you have same name variable in child.
Upvotes: 1