0

Why does the inherited method show_hp() of the class Knight doesn't use the class's variable hp, which was redefined in lower-in-hierarchy subclass?

I've tried overriding the method show_hp() and it worked, but I'm missing the concept of polymorphism, I think.

public class scratch {

    public static void main(String[] args) {
            Knight Ricardo = new Knight();
            Ricardo.show_hp();
        }


    static class Hero {
        int hp = 5;

        public void show_hp() {
            System.out.println(" I have " + hp + " hp!");
        }
    }


    static class Knight extends Hero {
        int hp = 3;
    }
}

I expect the output of 3, but the actual one is 5.

seenukarthi
  • 8,241
  • 10
  • 47
  • 68
  • 1
    Your problem is in re-declaring the variable hp. – ControlAltDel Aug 12 '19 at 18:17
  • 1
    The method that you're calling is in the `Hero` class, not the `Knight` class. Why would you expect it to print `3`? Fields cannot be overridden like methods can. – Jacob G. Aug 12 '19 at 18:18
  • 2
    Polymorphism doesn't apply to *fields*, only to *methods*. Your `Knight.hp` field is *hiding* the `Hero.hp` field. They are two different fields. – Andreas Aug 12 '19 at 18:18

2 Answers2

0

Ricardo here is an instance of class Knight, having

hp = 3

Therefore, if you want the value of hp to be 5, then you should override a method in the Knight class, calling the super class method.

Alternately, you can avoid re-declaring the hp variable in the sub-class.

Safeer Ansari
  • 772
  • 4
  • 13
0

To achieve what you want, you need to override the show_hp() method in the Knight class. You don't need to declare the hp member twice.

Because Knight extends Hero, the Knight class inherits the hp member anyways.

Polymorphic calls applies to the behaviour of a class, which means it's methods.

kevinj
  • 255
  • 2
  • 11