Hi everyone;
You can sometimes use same variable name in instance and in method or in child class and parent class.
Variable shadows
If the name of the variable in the method and the name of variable in instance are same, local variable in method shadows instance variable.
For example:
public class Test {
String x = "test";
Integer y = 10;
public void print()
{
String x = "test2";
Integer y = 20;
System.out.println("x :" + x);
System.out.println("y : + y");
}
public static void main(String[] args)
{
Test t = new Test();
t.print();
}
}
Output is :
x : test2
y : 20;
The variable in method shadowed the variable in instance.
To access variable of instance, you use this keyword
For example:
public class Test {
String x = "test";
Integer y = 10;
public void print()
{
String x = "test2";
Integer y = 20;
System.out.println("x :" + x);
System.out.println("y : + y");
System.out.println("this.x :" + this.x);
System.out.println("this.y : + this.y");
}
public static void main(String[] args)
{
Test t = new Test();
t.print();
}
}
Output is :
x : test2
y : 20;
this.x :test
this.y :10
Variable hides
If the name of the variable in the child class and the name of variable in parent class are same, the variable in child class hides the variable in parent class.
For example:
public class ParentHidingClass {
String x = "test";
Integer y = 10;
public void print() {
System.out.println("x : " + x);
}
}
public class ChildHidingClass extends ParentHidingClass{
String x = "test2";
@Override
public void print() {
System.out.println("x : " + x);
}
public static void main(String[] args) {
ParentHidingClass cls = new ChildHidingClass();
cls.print();
}
}
Output is :
x : test2
The variable in child class hides the variable of parent class.
To access variable of parent class, you use super keyword
For example :
public class ChildHidingClass extends ParentHidingClass{
String x = "test2";
@Override
public void print() {
System.out.println("x : " + x);
System.out.println("super.x : " + super.x);
}
public static void main(String[] args) {
ParentHidingClass cls = new ChildHidingClass();
cls.print();
}
}
Output is :
x : test2
super.x : test
I hope it was useful for you.
Thanx for reading