我是类和继承概念的新手,我想我可能有点困惑。我正在尝试使用 MVC 设计模式,所以我想如果我创建一个“基础”模型类,那么我可以从这个模型继承我的所有其他模型,以便 View 类可以接受对任何类型模型的引用。这是我的尝试:
public class SceneControl {
SceneView scMaze;
SceneView scOptions;
Model ms;
public SceneControl(ViewPanel view) {
this.view = view;
ms = new Maze(31, 20, 5);
SceneView scMaze = new SceneView(ms);
ms = new Options(20, 20, 20, 200, 20);
SceneView scOptions = new SceneView(ms);
...
这是我的扩展模型类之一:
public class Maze extends Model {
public int i;
public Maze(int cols, int rows, int ratio) {
super(cols, rows, ratio);
i=77; // a test- can I access this field from inside SceneView
}
}
但是当尝试访问 SceneView
中的额外 Maze
字段时,出现编译错误
public Model ms;
public SceneView(Model ms) {
this.ms = ms;
System.out.println(ms.i); //gives "connot be resolved or is not a field" error
...
所以我猜我的对象已经从 Maze
向下转换为 Model
?我如何将它传递给我的 View 类,就好像它是一个 Model
但它实际上仍然是一个 Maze
?
最佳答案
我想你想要的是这样的东西(取决于你是否定义了 Model
)。这假设 i
不是每个 Model
都会有的东西,否则将 i 移至 Model 的建议要简单得多(并将其保护为私有(private)并使用 setter/getter )。
public abstract class Model { // or even interface
public String modelAsString(); // possibly just use Object.toString()
}
public class Maze extends Model { // or implement, if Model is interface
private int i;
...
public String modelAsString() { return "i = " + i; }
}
public SceneView(Model ms) {
this.ms = ms;
System.out.println(m.modelAsString()); // Now any Model subtype will work
...
关于java - Java 中的类和继承——我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9335895/