Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we use the "new" keyword with an Interface in Java?

Tags:

java

oop

android

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.

like image 633
Arslan Ali Avatar asked Dec 06 '22 08:12

Arslan Ali


2 Answers

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:

  • The new operator
  • The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface OnClickListner.
  • Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: In the case of implementing an interface, there is no constructor, so you use an empty pair of parentheses, like in this example.
  • A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.
like image 176
PermGenError Avatar answered Dec 08 '22 22:12

PermGenError


Those OnClickListeners are anonymous classes. The brackets include the class definition.

like image 26
Robby Pond Avatar answered Dec 08 '22 21:12

Robby Pond