gpt4 book ai didi

Java:当我实例化抽象类的子类时,它无法识别其父类(super class)的构造函数

转载 作者:行者123 更新时间:2023-12-01 07:14:38 25 4
gpt4 key购买 nike

我没有太多的 Java 经验,但我看到代码中有一个带有特定构造函数的抽象类,然后是该抽象类的一个没有构造函数的子类。然后,当子类实例化时,它是用其父类(super class)构造函数构造的。是这样吗?

我有这个抽象类:

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: call to super must be first statement in constructor

我想创建一堆 Tile 的子类来实现 Tile 的属性。如果这不是正确的方法,那么更好的方法是什么?

如果有什么关系的话,我正在使用 32 位 Ubuntu Linux 11.04。

谢谢。

最佳答案

您的构造函数不是属性构造函数格式,它是void,请使其:

public Tile(int x, int y, int z){
this.x = x;
this.y = y;
this.z = z;
init();
}

关于Java:当我实例化抽象类的子类时,它无法识别其父类(super class)的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5862142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com