java - 子类需要设置父类的唯一对象字段吗?
问题描述
我有一个父类,它有一个声明的唯一 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);
解决方案
在这种情况下,泛型类可以与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;
}
}
推荐阅读
- javascript - 承诺 {
尽管使用了 async/await,但仍返回 - javascript - 反应数组中的元素。警告:React.createElement:类型无效
- laravel - npm 运行成功但终端进程停止(系统限制)
- python - 不和谐主题曲
- python - 需要帮助解析复杂的文本文件
- swift - Swift Dispatch Group 在函数中
- javascript - 更新时获取数字输入的值,使用 stepUp 或 stepDown
- javascript - 在 html 中包含 javascript 而不是链接到外部文件有缺点吗?
- java - 如何在 MongoDB 中查询字典数组中的数组?
- python - 我是 python 的初学者,我想用 tkinter 制作一个缺席号码队友随机程序