我正在玩Java游戏,目前正在尝试实现Menu系统。我有一个Menu
类和MenuBox
类,我想做的是在MenuBox
类中有一个抽象方法,自从每个{{ 1}}会产生不同的效果(暂停/取消暂停游戏,打开其他菜单,更改选项,保存游戏等)。
到目前为止,我已经添加了一个名为MenuBox
的接口,并且它仅包含方法Clickable
,该方法在activate()
类中被定义为空,我想在制作Menu对象时重新定义它。这有可能吗?我一直在研究,仅发现死胡同,但问题与我的不完全相同,因此我不确定这是否可能或我是否需要完全不同的方法。
这是接口和MenuBox类:
MenuBox
答案 0 :(得分:2)
您可以将MenuBox
类设为抽象类
public interface Clickable {
public abstract void activate();
}
public abstract class MenuBox implements Clickable{
private String label;
private int x,y,width,height;
public MenuBox(String label,int x,int y,int width,int heigth){
this.label = label;
this.x = x;
this.y =y;
this.width=width;
this.height=heigth;
}
}
然后,当您要实例化新的MenuBox时,可以定义抽象方法
MenuBox m = new MenuBox("",0,1,0,1){
public void activate(){
System.out.print("activated");
}
};
m.activate();
答案 1 :(得分:1)
您可以在MenuBox构造函数中注入一个类,以委派activate()方法的操作。像这样:
public class MenuBox implements Clickable{
private String label;
private int x,y,width,height;
private ActionClass action;
public MenuBox(String label,int x,int y,int width,int heigth, ActionClass action){
this.label = label;
this.x = x;
this.y =y;
this.width=width;
this.height=heigth;
this.action = action;
}
public void activate() {
this.action.activate();
}
}
ActionClass是一个接口,当activate()方法的行为不同时,可以在不同的场景中注入不同的实现。