无法使用来自父 class 的变量?

Unable to use variable(s) from parent class?

所以我需要在这段代码中有一个继承的例子,我试图得到它所以我在父 class 中实例化 private BufferedImage image,然后让它采用不同的形式在子 classes 中,例如 Player、Enemy 和可能的 Key。他们每个人都有自己的特定形象(这也是多态性的一个很好的例子吗?)。这是代码:

public class Entity { //hold things such as player, and values realted to that specific entity (nice especially for organization purposes)
Image i = new Image();
MazeModel model = new MazeModel();

private BufferedImage image; //they all have images
}

class Player extends Entity{
image = i.getPlayer();

public void setPlayerStart(){
    model.setPlayerX(50); //sets the starting x position of the player's image
    model.setPlayerY(50); //sets the starting y position of the player's image
}
}
//these next two I will possibly add later if I have the time
class Enemy extends Entity{
//nothing here for now
}

class Key extends Entity{
//nothing here for now
}

private class 的实例无法从 parent 继承到 child class 并且您无法在 [=23= 中访问] class.

所以 Entity class 的 private BufferedImage image;Player class.

中不可见

建议:尝试将此 private BufferedImage image; 设为 protected BufferedImage image; 以便您也可以在 child(Player) class 中访问您的实例变量也将是安全的。

将私有更改为 public。

public BufferedImage 图片;

我会使用 getter 和 setter 使其易于访问。

对于您的情况,您可以将每个内部值设为私有并通过 getter 和 setter:

访问它
public class Entity {
    private Image i;
    private MazeModel model;
    private BufferedImage image;

    // initialize these values when calling new
    public Entity() {
        this.i = new Image();
        this.model = new MazeModel();
    }

    // create getter and setter
    public BufferedImage getImage(){
        return this.image;
    }

    public void setImage(BufferedImage image){
        this.image = image;
    }

    public Image getI(){
        return this.i;
    }

    // other code...
}

class Player extends Entity {
    public Player(){
        this.setImage(getI().getPlayer());
    }

    //other code...
}

除了getter和setter,您需要创建构造函数(public Entity()和public Player())来初始化值。