gpt4 book ai didi

java - 通过子类实例调用时,如何在父类(super class)方法中使用子类的静态字段?

转载 作者:行者123 更新时间:2023-12-02 10:19:41 27 4
gpt4 key购买 nike

我有一个模型类,有一个名为 square 的子类。在模型类中,我有一个绘制方法,它需要子类中的一些字段。我有一个子类的实例,想要调用它的绘制函数(该函数不会在子类中被重写)。

我正在尝试在 Android 上使用 openGL 制作一些东西,并且有很多模型使用基本相同的代码来绘制,但使用不同的网格,因此具有不同的字段。我认为将绘制函数复制到每个模型类有点多余,当我尝试简单地在模型类上添加空字段和在子类上添加同名字段时,它在调用时使用父类(super class)中的字段使用子类实例的方法,也不能将字段作为参数传递,因为 super 构造函数调用必须是子类构造函数中的第一个调用,并且我需要对子类中的字段应用一些操作' 构造函数(我想,正如你所知,我对 OOP 没有经验)。

以下很多内容都是暂时的,因为我仍在努力掌握窍门

精简模型父类(super class):

abstract public class Model {
static final int COORDS_PER_VERTEX = 3;
final float Coords[];
public Model(){
//do some stuff unrelated to the issue
}
public void draw(){
final int vertexCount = Coords.length / COORDS_PER_VERTEX;
}
}

精简模型子类:

public class Square extends Model{
private static float Coords[] = {
-0.5f, 0.5f, 0.0f, // top left
-0.5f, -0.5f, 0.0f, // bottom left
0.5f, -0.5f, 0.0f, // bottom right
0.5f, 0.5f, 0.0f }; // top right
public Square() {
super();
//do something to Coords
}
}

方法调用:

private ArrayList<Model> models = new ArrayList<>();
models.add(new Square());
for (Model model:models) {
model.draw();
}

我希望绘制函数使用 vertexCount 的值 12/3=4,但它会引发 NullPointer 错误,因为您不能在 null 数组上使用 .length

最佳答案

因为继承不适用于字段。您的代码应该类似于

abstract public class Model {
static final int COORDS_PER_VERTEX = 3;
public Model(){
//do some stuff unrelated to the issue
}
public void draw(){
final int vertexCount = getCoords().length / COORDS_PER_VERTEX;
}
abstract public float[] getCoords();
}

public class Square extends Model {
private static float Coords[] = {
-0.5f, 0.5f, 0.0f, // top left
-0.5f, -0.5f, 0.0f, // bottom left
0.5f, -0.5f, 0.0f, // bottom right
0.5f, 0.5f, 0.0f }; // top right
public Square() {
super();
//do something to Coords
}

public float[] getCoords() {
return Coords;
}
}

abstract public class Model {
static final int COORDS_PER_VERTEX = 3;
protected float coords[];

public Model(float[] coords){
this.coords = coords;

//do some stuff unrelated to the issue
}
public void draw(){
final int vertexCount = coords.length / COORDS_PER_VERTEX;
}
}

public class Square extends Model {
public Square(){
super(new float[] {
-0.5f, 0.5f, 0.0f,
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
0.5f, 0.5f, 0.0f }
);
}
}

关于java - 通过子类实例调用时,如何在父类(super class)方法中使用子类的静态字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54427814/

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