Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Methods - Taking a method AS AN ARGUMENT

Tags:

java

methods

I've come across some code that I can't share here but it declares a method WITHIN the paramter list of another method. I didnt even know that was possible. I dont really understand why its doing that. Can someone please explain to me some possible uses that you as a programmer would have for doing that? (Note: Since I can't show the code I dont expect an in-context explanation just generally)

Related:

What's the nearest substitute for a function pointer in Java?

like image 339
Diego Avatar asked May 20 '09 11:05

Diego


1 Answers

Did the code look something like this?

obj.someMethod(myVar,3,new FooObject() {
  public void bar() {
    return "baz";
  }
});

If so, then the method is not being passed to the other method as an argument, but rather an anonymous inner class is being created, and an instance of that class is being passed as the argument.

In the example above FooObject is an abstract class which doesn't implement the bar() method. Instead of creating a private class that extends FooObject we create an instance of the abstract class and provide the implementation of the abstract method in line with the rest of the code.

You can't create an instance of an abstract class so we have to provide the missing method to create a complete class defintion. As this new class is created on the fly it has no name, hence anonymous. As it's defined inside another class it's an anonymous inner class.

It can be a very handy shortcut, especially for Listener classes, but it can make your code hard to follow if you get carried away and the in line method definitions get too long.

like image 94
Dave Webb Avatar answered Sep 30 '22 17:09

Dave Webb