Search code examples
javaencapsulation

Calling a parent method from a child class, encapsulation issues in Java


For some reason I can't figure out how to get this to compile. It cannot find the setValue function in this line: 'skill.get("Level").setValue(newLevel);'

import java.util.HashMap;

public class Stat extends GameObject
{
    int value;

    public Stat()
    {
        name = "Accuracy";
        value = 1;
    }

    public int getValue()
    {   
        return value;
}

    public void setValue(int newValue)
    {
        value = newValue;
    }
}


import java.util.HashMap; 

public class Skill extends Stat
{
    protected HashMap<String, GameObject> skill;

    public Skill()
    {
        name = "swords";
        description = "Learn how to master the art of swordmanship";
        skill.put("Level",new Stat("Level",1));
        skill.get("Level").setValue(newLevel);
    }
}

Solution

  • skill.get("Level") is a GameObject, not a Stat.

    Probably setValue is only defined in Stat, not GameObject?

    If you are sure (for instance if you checked with instanceof or only put Stat objects in the skill-HashMap) you can cast the result of the get to a Stat object, like this:

    ((Stat)skill.get("Level")).setValue(newLevel);
    

    Edit: probably just a copy paste problem: you need a constructor Stat(String, int) (thanks to Subhrajyoti Majumder for pointing that out)