【发布时间】:2015-01-06 19:00:00
【问题描述】:
所以我有一个超类 Ghost,在构造函数中有一个来自另一个类 Pacman 的参数。现在为了创建 4 种不同类型的幽灵(如果你喜欢吃 pacman,那就是兰迪、傻、特蕾西和苏),它们有很多相似之处,我正在制作 Ghost 的子类。在构造函数中,我从标题中得到错误。
Ghost.class的部分代码:
public class Ghost extends Actor
{
protected Pacman game;
Randy randy;
Ghost pinky; //totally unsure, but not a matter of question
public Ghost(Pacman game)
{
this.game = game;
这是 Randy 的子类:
private class Randy extends Ghost {
Actor randy;
public Randy(){
super(game); //here is the error
randy = new Actor();
this.game = game;
这就是我这样做的原因:
public void act()
{
if (pinky instanceof Randy){
moveRandom(); // Randy must move ONLY randomly unlike the other ghosts
}
setSlowDown(2);
code left out here
注意代码是零散的。
最后,我问这个问题,因为我还没有找到动态变量的解决方案。欢迎所有建议。
【问题讨论】:
-
你为什么要在自己内部存储每个类的实例? Randy 和其他 Ghosts 的实例不应该是 Pacman 游戏类中的类字段吗?为什么你首先需要传递一个 Pacman 实例来创建你的 Actor?
-
为什么你的
Ghost类有实例变量randy和pinky,两者都是Ghost类型或子类型?这似乎没有多大意义。 -
你能告诉我们
Actor构造函数吗?还有什么是Pacman?Ghost是否需要持有对Pacman的引用? -
@JohnBollinger 是的,当我现在考虑这个时。在 Actor 类上,它来自 JGameGrid 库。是的,我认为它必须如此。
标签: java inheritance constructor super