简体   繁体   English

从子类调用父方法,Java中的封装问题

[英]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);' 它无法在此行中找到setValue函数:'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. skill.get(“ Level”)是一个GameObject,而不是Stat。

Probably setValue is only defined in Stat, not GameObject? 可能setValue仅在Stat中定义,而不在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: 如果确定(例如,如果您用instanceof检查或仅将Stat对象放入Skill-HashMap中),则可以将get的结果强制转换为Stat对象,如下所示:

((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) 编辑:可能只是一个复制粘贴问题:您需要一个构造函数Stat(String,int)(感谢Subhrajyoti Majumder指出了这一点)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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