0xSina
0xSina

Reputation: 21553

Is this defining a new class or new instance?

New to java. Unclear about this piece of code:

ParseQuery query = new ParseQuery("GameScore");
query.getInBackground("xWMyZ4YEGZ", new GetCallback() {
  public void done(ParseObject object, ParseException e) {
    if (e == null) {
      // object will be your game score
    } else {
      // something went wrong
    }
  }
});

With new GetCallback() {....}, is it instancing an instance of GetCallback class or defining a subclass of Getcallback class or both?

Is this Java's way of doing anonymous functions in C/Objective-C and Ruby's blocks?

Upvotes: 1

Views: 121

Answers (3)

Sujay
Sujay

Reputation: 6783

Here's what you're doing:

  • You're declaring an anonymous inner class
  • You're instantiating it
  • Finally you're overriding the public void done(ParseObject object, ParseException e) method and providing your own definition of that.

The advantage of having such an anonymous inner class has to do with its usefulness when you want to use an instance of an object which certain tweaks to the actual functionality of the class such as overloaded methods (as in your case), without having to actually subclass a class.

Upvotes: 1

Drakosha
Drakosha

Reputation: 12155

It's anonymous classes, actually it's both creating a class and an instance. Some details here.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500055

It's doing both. It's declaring an anonymous inner class (you'll see a corresponding .class file in the compiled output) and creating a new instance of it.

Java doesn't have a way of creating just an anonymous function (as of Java 7) - this is as close as it gets though.

Upvotes: 7

Related Questions