I'm new to Android. I've studied in basic Object Oriented Programming courses that interfaces provide a way for classes to enhance their functionality. Classes who actually enhance their functionality this way, implement those interfaces and override all the methods written in interfaces.
Following code does the same job in Android:
public class MyActivity extends Activity implements OnClickListener {
// All other code you may expect
myButton.setOnClickListener(this);
@override
public onClick(View view) {
// Code when view is clicked
}
}
This code is understandable. But the following code makes no sense to me, I've searched it over different places but not getting a satisfied answer.
public class MyActivity extends Activity {
// All other code you may expect
myButton.setOnClickListener(new OnClickListner() {
@override
public onClick(View view) {
// Code when view is clicked
}
});
}
Now, OnClickListener()
is an interface as said in Android documentation, and, now we are instantiating an interface. Not interfaces are implemented only? Please help me understand this point.
new OnClickListner() {
is not instantiating an interface, it is declaring an anonymous inner class. basically an anonymous class(a class implementing the interface OnClickListner) which doesn't have a name per se.
From Documentation:
The anonymous class expression consists of the following:
Those OnClickListeners are anonymous classes. The brackets include the class definition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With