简体   繁体   中英

Creating a Class with specific methods in Java

I have 10 specific methods on my code, and I want to use them with a Class Object like this one:

void function(){
//do Something that I want
}

class PoseAction{

Pose pose;

void methodDesirable();

PoseAction(Pose ps, Method function()){

  this.pose = ps;
  this.methodDesirable() = function();
}

}

So when I create a new Object

PoseAction ps = new PoseAction(pose1, action1());

calling ps.methodDesirable();

it will call action1() function.

It's possible to do this?

Thanks in advance!

Functions are not first class objects in java. That is, you can not directly assign them or pass them as method parameters. You need to use objects and interfaces:

interface Action {
    void fire(Pose pose);
}

class PoseAction {
    Action action;
    Pose pose;

    void methodDesirable() {
        action.fire(pose)
    }

    PoseAction(Pose ps, Action a) {
        pose = ps;
        action = a;
    }
}

And use it like:

PoseAction ps = new PoseAction(pose1, new Action() {
     public void fire(Pose pose) {
          action1(pose);
     }
};
ps.methodDesirable();

No it's not possible in such way, Java doesn't support delegates . In java that can be done with interfaces:

interface Command {
    void doCommand();
}

PoseAction pa = new PoseAction(new Pose(), new Command() {
    @Override
    public void doCommand() {
        //method body
    }
});

Here new Command() {...} is anonymous inner class that implements Command Interface

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM