• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Declaring methods as part of a newly constructed instance?

I have a mega stupid question, but I can't seem to find the right wording in Google to find the answer.

In several of the tutorials I've gone through, the following syntax is used:

        Handler handler = new Handler()
		public void handleMessage(Message msg)
                     //do stuff

1) What is this achieving? Is this allowing you to override one particular method for only THAT instance that you've just created, without needing to extend the entire class?

2) What is this syntax best called or described as? I tried Googling for stuff like, "declare method inside new instance" and such, and got nothing.

3) Are there any best practices/potholes that I should be aware of in using this? (e.g. "it's generally discouraged", etc.)

1) Handler is an abstract class. Java doesn't let you instantiate an abstract class because some methods have not been implemented. The syntax you see above is an inline class definition. It allows you to define an abstract class and instantiate it all in one go. Some people see this as poor and cluttery code, but in Android dev, it's a pretty standard practice, especially for listeners and other callbacks. I should note, however, that if you do this, you must override every abstract method in the class, even if you don't need it. You can't just pick and choose methods.

2) inline class definition. some people also call it an inner class, but this isn't quite accurate enough as an inner class doesn't necessarily need to be inline.

3) like I said in #1, some people see it as poor coding practice, but in Android dev, it's pretty standard.
  • Like
Reactions: CptSupermrkt
Upvote 0


We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.