user186984
user186984

Reputation:

What is this type of method overriding called in Java?

I'm relatively new to Java and I'm using a new API. I came across this method override and I'm not sure what this is called:

public void exampleMethod() {
    Button loginButton = new Button("login"){
       public void onSubmit(){
          //submit code here
       }
    };
}

From what I understand, this is overriding the onSubmit method of the Button class. I've never come across this type of overriding before. Is there a specific name for it? I want to read up more about it but I can't find it. All my searches so far result to regular method overriding by creating a new class, which is what I'm already familiar with.

I'd appreciate if someone could point me in the right direction.

Thanks.

Upvotes: 44

Views: 13916

Answers (3)

David Webb
David Webb

Reputation: 193716

That's an anonymous inner class.

In the example above instead of creating a private class that extends Button we create an subclass of Button and provide the implementation of the overridden method in line with the rest of the code.

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.

Upvotes: 40

Jesper
Jesper

Reputation: 206816

That is an anonymous inner class.

More info: Anonymous classes

Upvotes: 7

Jon Skeet
Jon Skeet

Reputation: 1500665

That's an anonymous inner class. Basically it creates a new class which derives from the specified one (Button in this case, although you can use the same technique to implement interfaces) and overrides appropriate methods. It can contain other methods as well, but they'd only be available within that class.

The class has access to final local variables within the same method, and if you're writing an instance method it has an implicit reference to this as well (so you can call other methods in your "main" class).

Upvotes: 13

Related Questions