Parent and child class having same variable - "name," which has been accessed through inherited method - getName() in Parent Class
class A {
String name = "A";
String getName() {
return name;
}
String greeting() {
return "Class A";
}
}
class B extends A {
String name = "B";
String greeting() {
return "Class B";
}
}
public class Client {
public static void main(String[] args) {
A a = new A();
B b = new B();
System.out.println(a.greeting() + " has name " + a.getName());
System.out.println(b.greeting() + " has name " + b.getName());
}
}
Output:
Class A has name A
Class B has name A
In the above snippet, b.getName() returns the output as "A" though accessed using child class reference. Can someone pls explain this?
Note: I have visited this link already - Overriding member variables in Java ( Variable Hiding), where in that link, the variable is accessed directly using the reference. In the given code snippet above, it has been accessed through the inherited method, which produced the output using the parent class variable, though called via the Child Class reference and Child Class Object.