[英]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.