Question

So I want to make a game engine, and I instantly realized that stuff has to be "auto-imported". For example, when you implements Runnable, you get an error because it HAS to have the run() method in the class.

How do you do this? How would i have a class, when implemented, FORCE a method, and then automatically run this method?

An example, usable when answering:

I have a Frame class. This frame class will, when implemented, ALWAYS use a method, in the class that implemented it, named draw(), and will HAVE to be implemented to use the frame class. Example code:

public class test implements HFrame {
    // constructor
    public test() {

    }

    // method called when test is run
    public static void init() {
        HFrame f = new HFrame(WIDTH, HEIGHT);
        f.display(); // makes the frame visible
    }

    // method that frame will always call when it is implemented
    public void draw() {
        // stuff to draw
        new Circle(0, 0, 50, 50);
    }
}

using the comments, how would i get this to work?

thanks for the help, and i apologize if this isnt worded the best...

Was it helpful?

Solution

In order to "force" a class to implement certain methods you use an interface, an example of which is below

public interface GameEngineInterface {
    void init();
    void draw();
    Vector3d annotherMethod(Object object);
}

Any class that is going to be used by your Game engine would implement the GameEngineInterface engine.

GameEngine methods would work as such

public Object someMethod(GameEngineInterface anyObjectThatImplementsGameEngineInterface){
    //method body
}

The GameEngine then doesn't care about the specifics of the implimenting methods, just that it can call those methods.

OTHER TIPS

Create an interface with the methods that you want to run. All the classes that will be used must implement that interface. This is exactly how Runnable works: Runnable is an interface with one method void run() that the Thread can call to execute the runnable.

Looks like you need to implement the Template Method design pattern. In your example, run would call draw(), which must be implemented in the concrete class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top