【发布时间】:2011-05-02 20:32:50
【问题描述】:
我没有太多 Java 经验,但我看到代码中存在具有特定构造函数的抽象类,然后是没有构造函数的抽象类的子类。然后当子类被实例化时,它是用它的超类构造函数构造的。对吗?
我有这个抽象类:
public abstract class Tile{
public int x;
public int y;
public int z;
protected Color color;
protected float friction;
protected float bounce;
protected boolean liquid;
public void Tile(int x, int y, int z){
this.x = x;
this.y = y;
this.z = z;
init();
}
abstract protected void init();
还有这个子类:
public class TestTile extends Tile{
protected void init(){
color = Color.RED;
friction = 0.1f;
bounce = 0.2f;
liquid = false;
}
}
但是当我用这个实例化一个 TestTile 时:
Tile tile = new TestTile(0, 0, 0);
init() 方法永远不会运行。它里面定义的所有值都是空的。我尝试在子类中创建一个我认为可能是冗余的构造函数,它只是使用完全相同的参数调用 super,但是当我这样做时,即使 super(x, y, z) 是其中唯一的语句,它也会这样说:
TestTile.java:27:对 super 的调用必须是构造函数中的第一条语句
我想创建一堆 Tile 的子类来实现 Tile 的属性。如果这不是正确的方法,还有什么更好的方法?
如果与任何事情有关,我正在使用 32 位 Ubuntu Linux 11.04。
谢谢。
【问题讨论】:
标签: java class constructor subclass abstract