Michał Gwóźdź
Michał Gwóźdź

Reputation: 105

What am I doing wrong with inheritance?

I'm trying to write simple game to test some new features in Java. I have Class Monsters and there is int hp:

public class Monsters {
    int hp;

    public Monsters() {
    }
    public Monsters(int hp) {
        this.hp = hp;
    }
    }

And then I have two subclasses - a main hero HERO, and his oponent Devil. They also have int hp, because their life level is different:

public class Devil extends Monsters {

    int hp = 200;
}

and HERO:

    public class HERO extends Monsters{
    public HERO(int hp) {
        this.hp = hp;
    }
    }

I'm trying to write fight(); method:

public void fight(Monsters hero) {
        int heroLife = hero.hp;
        int opLife = hp;
        System.out.println(opLife + " - Devil's life\n"
                + heroLife + " - Hero's life");
}

Ok, and now in main() class Game i'm testing their hp:

public class Gra {
   public static void main(String[] args) {
   HERO hero = new HERO(5);
   Devil devil = new Devil();
   devil.fight(hero);
   }
}

And here's my output:

0 - Devil's life
5 - Hero's life

Why is it 0, not 200?

Upvotes: 2

Views: 147

Answers (3)

Harshit
Harshit

Reputation: 163

You are not defining default constructor at your devil class. First implement default constructor inside default constructor use super keyword.

public class Devil extends Monsters 
{
  public Devil() {
   super();
    this.hp = 200;
  }
}

Upvotes: 0

Tanmay Patil
Tanmay Patil

Reputation: 7057

Problem

You are creating new hp field and hiding inherited hp.

Solution

Replace

public class Devil extends Monsters {

    int hp = 200;
}

with

public class Devil extends Monsters {
    public Devil() {
        this.hp = 200;
    }
}

Good luck.

Upvotes: 3

Eran
Eran

Reputation: 393771

You have a hp variable in both Monsters class and Devil class. When you access hp from a method of Monsters class (your filght method), you get the variable of hp, which is 0 by default.

You should have hp only in the base class, and use Monster's constructor to initialize it properly :

For example :

public class Devil extends Monsters 
{   
    public Devil () 
    {
        super(200);
    }
}

Upvotes: 4

Related Questions