I am learning Java. I have a doubt about inheritance.
When a child class extends parent class and parent class has a method which refers to a instance variable declared in parent. But the child class didn't override this method and has declared instance variable with same name as the parent. In this case instance variable from child will be referred or parent will be referred.
Below is the code snippet:
class Parent {
int a;
Parent() {
System.out.println("in Parent");
a = 10;
}
void method() {
System.out.println(a);
}
}
class Child extends Parent {
int a;
Child() {
System.out.println("in Child");
a = 11;
}
}
public class Test {
public static void main(String args[]) throws IOException {
Parent p1 = new Child();
p1.method();
}
}
The output I get is
in parent
in child
10
I want to understand why its referring parent class's instance variable a and not child class's a.
Another doubt is, I understood hiding the method, when there is a static method in parent and child class also has declared a static method with same signature. What does hiding mean here? What method is getting hidden? If it's the parent method, why is this?
method()