why can't I call a subclass method using a reference of a parent type that refers to an instance of a sub-type

I am Learning Java, while trying to understand inheritance. I couldn't figure out why the overridden method at the subclass walk() executed but not the other xyz() method.

   class Person{
     public void walk() { System.out.println("walking like a person "); }

   public class Soldier  extends Person{
    public void walk() { System.out.println("marching like a  soldier "); }
    public void xyz()   { System.out.println("xyzng like a pro"); }

    public static void main(String[] args) {

        Person sp = new Soldier();

Here is my question, if the following method call works fine and calls the Soldier method walk,


why the compiler complain about the this call?

5 Answers
  1. At the compile time parent class reference 'sp' can only see method inside it. if you want to access as ((Soldier) sp).xyz()

    Narendra Gupta2015-08-29 08:30:46
  2. You may want to take a look at this answer.

    Basically, xyz method is defined in a subclass of Person and in general case compiler can't know (and should not know) whether the referenced instance is Soldier or some other subclass which does not define xyz method.

    Dragan Bozanovic2015-08-29 08:25:58
  3. In Java, "objects" are not values themselves -- they must always be manipulated through references; when you create an object, you get a reference; when you access a field or call a method, you do it through the reference. When you assign one reference to another, it copies the reference, so you have multiple pointers to the same object.

    Your question asks why Soldier.xyz() is not accessible when the Soldier object is stored in a Person reference. The answer is the intersection of "polymorphism" and "static typing". Because Java is statically typed at compile time you get certain guarantees from the compiler but you are forced to follow rules in exchange or the code won't compile. Here, the relevant guarantee is that every instance of a subclass (e.g. Soldier) can be used as an instance of its super class (e.g. Person).

    Please take a look at this it is explained in more details thread As of the tutorial guide to truly understand the inheritance please take a look at this article

    Ilia Aptsiauri2015-08-29 08:26:05
  4. That's clear. because your reference to object(sp) is of type Person, that means sp contains all property and methods of Person only. Even you get instance of Soldier, but your reference is from Person type yet.

    amin100432015-08-29 09:02:08
    • Person is a class.
    • sp is an object, it is an instance of Person
    • Class Person haven't method named xyz(), thereforce sp.xyz() not working.

    why can't I call a subclass method using a reference of a parent type that refers to an instance of a sub-type

    (You have a typo, we use @Override, not @override)

    2015-08-29 09:22:35
Related Articles
You Might Also Like