pool matho
pool matho

Reputation: 39

How to implement object specific methods?

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
    }
}

Upvotes: 1

Views: 87

Answers (2)

Hacketo
Hacketo

Reputation: 4997

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();

Upvotes: 2

You can inject a class in the MenuBox constructor to delegated the action of the activate() method. Something like this:

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 is an interface and you can have differente implementation of it being injected in different scenarios when activate() method has different behaviors.

Upvotes: 1

Related Questions