Flash Flash - 5 months ago 6x
Java Question

Is it possible to overwrite an object's tick method in it's constructor?

I'm making a game UI from scratch and rather than create a class for many similar objects, such as the FPS and score counters.
Is it possible for me to create a single class that allows me to overwrite their basic tick methods in a similar way to how I'm overwriting the onClick() methods on my buttons?

hudUIManager.addObject(new UIImageButton(handler, handler.getWidth()/2-128, handler.getHeight()/2-32, 64, 64, Assets.button_menu, new ClickListener(){
public void onClick() {

Feel free to tell me I'm going about this completely the wrong way as long as you can point me in the right direction. Any and all help is appreciated!


A way to do that would be to create a class which takes an interface in its constructor. Then when you instantiate the class, you would pass in an implementation of the interface as an anonymous class as you do when you pass in the ClickListener in your example.

For instance, the interface may be something like

public interface Ticker() {
    public void doTick();

Then the base class may be something like

public class TickObject() {
    private Ticker ticker;

    public TickObject(Ticker ticker) {
         this.ticker = ticker;

    public void doTick() {

Then when you want to create an instance of TickerObject it would be as follows

TickObject tickerObject = new TickObject(new Ticker(){
    public void doTick() {
        // implement