I'm playing around with a Java game, and I'm currently trying to implement a Menu system. I have a Menu
class and MenuBox
class, what i'd like to do is have an abstract method in the MenuBox
class that i would define somewhere else in the code since every MenuBox
can have a different effect (pause/unpause game, open a different menu, change options, save game ect...).
So far I've added an Interface called Clickable
, and it only has the method activate()
in it which is defined as empty in the MenuBox
class, and i'd like to redefine it when making a Menu object. Is this even possible ? I've been researching and only found dead ends but the questions were not exactly the same as mine so i'm not sure whether this is possible or if i need a completely different approach.
Here are the interface and MenuBox class:
public interface Clickable {
public abstract void activate();
}
public 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;
}
public void activate() {
//Empty method to redefine outside the class i.e. after instantiation
}
}
You can make the MenuBox
class an abstract class
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;
}
}
Then when you want to instanciate a new MenuBox you can define the abstract method
MenuBox m = new MenuBox("",0,1,0,1){
public void activate(){
System.out.print("activated");
}
};
m.activate();