[英]How do I use a subclass' static fields in superclass' method when calling via instance of subclass?
我有一个模型类,有一个名为Square的子类。 在模型类中,我有一个draw方法,该方法需要子类中的一些字段。 我有一个子类的实例,想调用其draw函数(在子类中不要重写)。
我正在尝试在Android上使用openGL进行制作,并且有很多模型使用基本相同的代码进行绘制,但是使用不同的网格,因此具有不同的字段。 我认为将draw函数复制到每个单独的模型类有点多余,并且当我尝试在模型类上简单地添加空字段以及在子类上添加相同名称的字段时,在调用时会使用超类中的字段同样,使用子类实例的方法也不是必须将字段作为参数传递,因为超级构造函数调用必须是子类的构造函数中的第一个调用,并且我需要对子类中的字段进行一些操作”构造函数(如您所知,我对OOP没有经验)。
以下内容是暂时的,因为我仍在尝试摆脱困境
精简的模型超类:
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();
}
我希望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 }
);
}
}
您可以编写一个返回Coords
数组的getter方法。 这样,每个子类都可以覆盖它以返回不同的变量。
abstract public class Model
{
protected float[] getCoords() {
return Coords;
}
}
public class Square extends Model {
@Override
protected float[] getCoords() {
return Coords;
}
}
我知道在实例方法中返回static
实例变量没有多大意义,但是您只能覆盖实例方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.