when i run this code display method of derived class is being called
Looks like you have programmed in other programming languages like C++ or C# where you must specify the method as virtual
in order to use the subclass method. In Java, all the methods except private
, final
and static
are virtual.
Knowing this, since Child
class already overrides display
method from Parent
class, when you do this:
Parent a1 = new Child();
a1.display();
a1.display
will execute the display
method of the actual object reference class, in this case, Child#display
.
In order to fix the code, change the initialization of a1
to be a new Parent
:
Parent a1 = new Parent();
a1.display();
More info:
After your edit, now you face the problem when printing a1
in the console, probably printing 9
instead of 8
. What you're doing here is hiding the field. Fields do not get overridden, so the value of the i
variable will depend on the actual class type declared for the variable. Since you have declared a1
as Parent
, then a1.i
will take the value of Parent#i
.
In order to fix this code, change the a1
variable type to Child
:
Child a1 = new Child();
System.out.println(a1.i);
a1.display();
Or a even better solution: NEVER try to override a field, and what's worse, don't try to access to class fields from other classes directly, instead use the respective getters and setters.
More info:
How to access methods of ancestor class when intermediate parent class overrides it?
Assuming this is your real question, then the answer is simple: you can't.