Reputation: 4202
public class AbcMain {
public static void main(String[] args) {
Parent p = new Child();
p.sayHello();
System.out.println(p.a);
}
}
class Parent{
int a = 10;
public void sayHello(){
System.out.println("Hello inside parent.");
}
}
class Child extends Parent{
int a = 20;
public void sayHello(){
System.out.println("Hello inside child. ");
}
}
Output is : Hello inside child. 10
Confused here, It is calling the method of Child() as the instance is of child. Then why it prints a = 10?
Upvotes: 1
Views: 130
Reputation: 1688
Since the object type is Parent
, p
will have all the characteristics of an Parent
. But, since the object created is a Child
, any overridden methods in the Child
class will be used instead of those in the Parent
class. That's why you got Hello inside child
as first output.
As, Child
is a subclass of Parent
, First, Child
default constructor will be invoked, and so a
is initialized to 20
, then there will be a call to Parent
default constructor and the value in variable a
becomes 10
and thus you will get the second output as 10
(The first line in your Child
constructor would be super()
by default unless you call an overloaded constructor of Child
using this()
).
Upvotes: 0
Reputation: 121998
In java method overriding is there. No variable
overriding.
Just for testing change the variable name in parent to parentA
and see :)
Upvotes: 2
Reputation: 35557
Your Parent p
is Child
type. Now p
is a Child
instance. So now you are invoking Child
s properties. And Child
will override Parent
sayHello
method.
You should learn about Java polymorphism and inheritance.
Upvotes: 1
Reputation: 32949
There is no "overriding" of fields in Java as there is with methods. So you could think that since Child
overrode satHello
only one instance of the method exists (for the perspective of other classes). However, with fields both instances exist. Therefore Parent.a = 10
and Child.a = 20
. Since p is declared as Parent
you got 10.
Upvotes: 1