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.
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.