Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Simple Android App Improving Our Code Simple Refactoring: Using a New Class

Adam Sawicki
Adam Sawicki
15,967 Points

Syntax Confusion

Hey,

Please explain me code below. I don't understand here few things:

  1. If View.OnClickListener is inteface shouldn't it be implemented rather than creating object?

  2. Why after "new View.OnClickListener()" there is curly bracket and directly after creating new object there is overriding a method. Shouldn't it be : "View.OnClickListener listener = new View.OnClickListener();" and then overriding a method?

View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View v) { mFactTextView.setText(facts[randomNumber]); } };

Basically it creates a new object so you don't have to write more lines than you have to and that's what android auto complete is for. In a later course you do implement it, but when your making a simple app with only a few classes, it is easier to create an object. When you create an object it creates a inner method when you can write your on click in. You don't do View.OnClickListener listener = new View.OnClickListener(); because that assigns it to a variable which you wont use again in the future. All of this is just a custom, and it doesn't really affect the functionality of the code.