0

So you can do generic types with <> and you can pass objects with (). But what is it called when you pass information with {}, as in this example?

new Filter<CLDevice>() {
    public boolean accept(CLDevice device) {
        CLDeviceCapabilities caps = CLCapabilities.getDeviceCapabilities(device);
        return caps.CL_KHR_gl_sharing;
    }
}

Also does this work only for constructors or can any method make use of {} to gather data?

Is there any caveats associated with such code, like is it not performant?

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
Thomas
  • 6,032
  • 6
  • 41
  • 79
  • 4
    `<>` and `()` and `{}` are completely unrelated - they're not instances of a "information passing" concept or anything. – user253751 Jul 21 '14 at 09:31
  • Your example simply shows an [anonymous class](http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html). Note, that the `{}` are used in various scenarios: class declaration, block code declaration (methods, loops, etc.), and in array initializers. – Seelenvirtuose Jul 21 '14 at 09:36
  • If you want the name of the concept, well in your example you're using an ANONYMOUS CLASS. here is a [question](http://stackoverflow.com/questions/355167/how-are-anonymous-inner-classes-used-in-java) about using them. Usually, inside {} you will implement some methods that are related to the class (`Filter` here). – DenisFLASH Jul 21 '14 at 09:37

4 Answers4

2

In this case you are providing an implementation via an anonymous class for a Single Abstract Method (SAM) interface or functional interface.

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
2

In java { and } define scope. There are various type of scopes for example class, method, block.

In your example your are creating a anonymous class.

2

What you are showing is not actually passing information (like passing an argument to a method), it's passing behavior.

Because up until Java 7 no lambdas existed, in order to pass behavior you always needed a class (after all in the java world everything a class). The syntax you are showing, is the syntax for an anonymous inner class. This syntax is used as a shortcut when you don't need/want to create a new class file, but just need to pass some behavior.

Note that you could just as easily use the same syntax if you had to implement (behavior passing) more than one method - something you could not do with Java 8 lambdas.

geoand
  • 60,071
  • 24
  • 172
  • 190
0
So you can do generic types with <>.

You can pass objects with ().

What is it called when you pass information with {}, as in this example

With {} you create a body of a method or an anonymous class/method/object.. here your code is defining an anonymous method.

Deepanshu J bedi
  • 1,530
  • 1
  • 11
  • 23