Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing in lambda - java

Tags:

java

I have created a class named Player and a class named Car , which has a method called isOwner(Player player). It has a constructor that is like this:

public Car(String name, Action<Player> action) {
        this.name=name;
        this.action = action;
}

Now in my main code I want to do this:

Car car1 = new Car("BMW", (input ->{
            if (this.isOwner(input)){
                // code 
            }
           }));

But here this references the class I am writing inside (e.g. Main class); also if I put car1 instead of this, it will give error saying car1 may not be initialized.

like image 260
Erik Hartouni Avatar asked Sep 20 '25 04:09

Erik Hartouni


1 Answers

I would go for a good old-fashioned unfashionable anonymous inner class.

Car car1 = new Car("BMW") {
    @Override protected action(Player input) {
        if (isOwner(input)) {
            // code 
        }
    }
};
like image 82
Tom Hawtin - tackline Avatar answered Sep 22 '25 18:09

Tom Hawtin - tackline