Java – Why do we use the “new” keyword in Java’s interface?

Why do we use the “new” keyword in Java’s interface?… here is a solution to the problem.

Why do we use the “new” keyword in Java’s interface?

I’m new to Android. I learned in basic object-oriented programming classes that interfaces provide a way for classes to enhance their functionality. Classes that actually enhance their functionality in this way, implement these interfaces and override all methods written in the interface.

The 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 code below makes no sense to me, I searched in different places but didn’t get a satisfactory 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 that OnClickListener() is an interface in the Android documentation, we are instantiating an interface. Isn’t the interface just implemented? Please help me understand this.

Solution

new OnClickListner() { does not instantiate the interface, it declares one anonymous inner class Basically an anonymous class (a class that implements the interface OnClickListner) that has no name of its own.

From Documentation :

An anonymous class expression consists of the following parts:

  • New carriers
  • The

  • name of the interface to implement or the class to extend. In this example, the anonymous class is implementing the interface OnClickListner.
  • Include parentheses for constructor parameters, just like a normal class instance creation expression. Note: In the case of implementing an interface, there is no constructor, so you use a pair of empty parentheses, as shown in this example.
  • A principal, which is a class declaration principal. More specifically, in the body, method declarations are allowed, but statements are not.

Related Problems and Solutions