Need a clarification on below code, why it is printing the output 10 instead of 20 | Core Java Forum
Vikrant Posted on 07/09/2021

Hello Yogesh,

Please help me with below code.

I have created a class A and extends the same in B and then in another class I have mentioned the parent on right and child on left 

then I am printing the value of a using object then its printing 10 instead 20, can you please tell me why its printing 10?

Yogesh Chawla Replied on 09/09/2021

Because variable 'a' is overridden in child class with value 20 so when you create the object like this:

Parent obj  = new Child();

You are somewhat saying that I am interested in the fields and methods of Parent but if they are overridden in Child then through the concept of Inheritance, I am going to get the child class implementation only and if their implementation is not available in child then of course in that case only, I will get the implementation of Parent.

Vikrant Replied on 10/09/2021

Ohh got it, if implementation is missing in child class then it will pick the data or value from Parent class. Thanks


Vijay Replied on 11/09/2021

Here child class is over rides with variable a 20 then 20 should be printed right

Yogesh Chawla Replied on 16/09/2021

Yes. Right