首页 > 解决方案 > 子类需要设置父类的唯一对象字段吗?

问题描述

我有一个父类,它有一个声明的唯一 ModelType 对象,它也有子类。每个子类都有一个唯一的模型类型,因此我希望引用变量“模型”在所有子类中都相同,因此可以引用该变量。但是,在将模型类型初始化为任何子对象后,我的函数会引发错误,因为在这种情况下,类型不是 ModelType,而是 Cuboid 或 Pyramind(其中一个子对象)。

可能有比创建父级并将其设置给子级更好的方法。如何在父类中有一个可以设置为多种类型的引用变量?换句话说,变量“模型”需要是不同的类型。

class Parent {
  ModelType model;
}

class ChildOne extends Parent {
   model = new Cuboid();
   void float vertices(Pyramid c){
      // ... stuff ...
   }
}

class ChildTwo extends Parent {
   model = new Pyramid();

   void float vertices(Pyramid c){
      // ... stuff ...
   }
}

将另一个 ChildTwo 的“模型”传递给该类时使用顶点时出现错误,其中:

The function vertices(ModelType) doesn't exist


ChildTwo a = new ChildTwo();
ChildTwo b = new ChildTwo();
a.vertices(b.model);

标签: javaobjectinheritance

解决方案


在这种情况下,泛型类可以与Upper Bouded WildCard一起使用,以便vertices可以根据子类类型参数限制该方法接受参数。

abstract class Parent<T extends ModelType> {
    T model;

    abstract float vertices(T c);

    // To set the model, setter can be created in parent class.
    // Or through constructor of child class.
    void setModel(T modelToSet) {
        this.model = modelToSet;
    }
}

class ChildOne extends Parent<Cuboid> {
    ChildOne(Cuboid c) {
        this.model = c;
    }

    float vertices(Cuboid c) {
        // ... stuff ...
        return 0;
    }
}

class ChildTwo extends Parent<Pyramid> {
    ChildTwo(Pyramid p) {
        this.model = p;
    }

    float vertices(Pyramid p) {
        // ... stuff ...
        return 0;
    }
}

推荐阅读