Consider below code
class A
{
int x = 5;
void foo()
{
System.out.println(this.x);
}
}
class B extends A
{
int x = 6;
// some extra stuff
}
class C
{
public static void main(String args[])
{
B b = new B();
System.out.println(b.x);
System.out.println(((A)b).x);
b.foo();
}
}
Output of the program is
6
5
5
I understand the first two but can't get my head around the last one. How does b.foo() print 5. B class will inherit the foo method. But shouldn't it print what b.x would print? What exactly is happening here?
If the superclass and the subclass have instance variable of same name, if you access it using the subclass object, the instance variables of the subclass hides the instance variables of the superclass irrespective of the types. This mechanism is known as field hiding or, instance variable hiding.
Method hiding can be defined as, "if a subclass defines a static method with the same signature as a static method in the super class, in such a case, the method in the subclass hides the one in the superclass." The mechanism is known as method hiding. It happens because static methods are resolved at compile time.
The shadowed instance variable can be accessed using the this keyword. Variable hiding happens when a variable declared in the child class has the same name as the variable declared in the parent class. The hidden variable of the parent class can be accessed using the super keyword.
In Java, if there is a local variable in a method with the same name as the instance variable, then the local variable hides the instance variable. If we want to reflect the change made over to the instance variable, this can be achieved with the help of this reference. Example: Java.
Yes, the B
class inherits the foo
method. But the variable x
in B
hides the x
in A
; it doesn't replace it.
This is an issue of scope. The foo
method in A
sees only the variables that are in scope. The only variable in scope is the instance variable x
in A
.
The foo
method is inherited, but not overridden, in B
. If you were to explicitly override foo
with the same exact code:
class B extends A
{
int x = 6;
@Override
void foo()
{
System.out.println(this.x);
}
}
Then the variable that would be in scope when referred to by this.x
would be B
's x
, and 6
would be printed. While the text of the method is the same, the reference is different because of scope.
Incidentally, if you really wanted to refer to A
's x
in the B
class, you can use super.x
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With