简体   繁体   中英

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);
    }
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM