John Doe John Doe - 2 months ago 19
Java Question

Initializing a subclass Object

I'm in a dilemma in which I cannot initialize one of my objects. I've got a superclass called

Gamepiece
and then a class that extends
Gamepiece
called
Item
. Here's my
Gamepiece
code:

public class Gamepiece
{
String name;
char icon;

public Gamepiece(String newName, char newIcon)
{
this.name = newName;
this.icon = newIcon;
}
}


And here's
Item
:

public class Item extends Gamepiece
{
int weight, type;
int hit, def;

public Item(String nname, char nicon, int nweight, int ntype)
{
name = nname;
weight = nweight;
type = ntype;
icon = nicon;
}
}


When I try to use
Item example = new Item("Nothing",'0',0,0);
it compiles fine I get the following runtime error:

Exception in thread "main" java.lang.NoSuchMethodError: Gamepiece: method <init>()V not found
at Item.<init>(Item.java:7)
at rogue.main(rogue.java:8)


What's my issue and how can I fix it?

Answer

You have to invoke the constructor of the superclass, this is possible by using the super() method.

The code of your subclass would be:

public class Item extends Gamepiece
{
    int weight, type;
    int hit, def;

    public Item(String nname, char nicon, int nweight, int ntype)
    {
        super(nname, nicon);
        weight = nweight;
        type = ntype;
    }
}