Search code examples
javaclassmethodsbehavior-tree

In Java, how can I create a class whose methods are different in each instance?


I'm working on a basic game AI, and I'm trying to encapsulate the transitions between nodes in a behavior tree using an abstract class called Transition.

Right now, Transition looks like this:

package com.game.behaviors;

public abstract class Transition {
    public abstract Node getNextNode();
}

What I'd like to be able to do is to specify the logic inside the method getNextNode on each instance of Transition. Some transitions, for example, will always return the same Node, while others may return one of several nodes based on either a random number generator or on some other logic.

I know that I can achieve this by creating a class that inherits from Transition for each behavior I want, and then getting instances of those classes, like so:

class RealTransition extends Transtition{
    Node thisNode = someNode;

    public Node getNextNode(){
        return thisNode;
    }
}

RealTransition rt = new RealTransition();
someObject.someMethodThatWantsATransition(rt);

As a Java noob that mostly works in Javascript, this feels clunky. Creating a new class that I know I'm only going to instantiate once feels like it should be unneccesary, especially since I'm probably going to define lots of transitions. Is there a better way I can go about defining how my transitions work?


Solution

  • As @ajb stated, you can do the same thing using Functional Interfaces from Java 8. It is basically the same, but you use anonymous classes to pass your desired behavior.

    Define your Transition like this:

    @FunctionalInterface
    public interface Transition {
        public Node getNextNode();
    }
    

    Then use it in your method with a lambda expression:

    someObject.someMethodThatWantsATransition(() -> {
        // your method body here;
    });
    

    Since any Functional Interface can only have one method, a new Transition is instantiated and it's only existing method is called.