java - Why am I able to access child methods in the parent class? -
java - Why am I able to access child methods in the parent class? -
i have problem understanding of inheritance in java: able access overwritten methods of kid class when cast parent class.
as illustration there given 2 next classes:
the parent one:
public class parent { public void whatareyou() { system.out.println("parent"); } }
and kid class:
public class kid extends parent { @override public void whatareyou() { system.out.println("child"); } public void onlychildrencandothis() { //... } }
when following:
kid c = new child(); parent p = c; p.whatareyou();
i output:
child
this unusual understanding of inheritance in java. expect parent
output, because narrowed kid class parent class, , should have access variables , methods of parent class.
this working p.onlychildrencandothis()
, cannot access it, because not implemented in parent class...
...but overwritten methods java not behaving way! why that?
here's have done
child c = new child();
you created object of kid class , assigned reference c.
parent p = c;
here have copied reference of kid object p. remember object still child's object not parents's object.
p.whatareyou();
here have called whatareyou method. calling using reference variable p pointing object of child. hence child's method called.
another interpretation
java inheritance
Comments
Post a Comment