Why do we use the “new” keyword with an interface in Java?

I'm new to Android. I've learned the basic object-oriented programming courses, which provide a way to enhance the functions of the courses. In fact, the classes that enhance their functions in this way implement these interfaces and cover all the methods written in the interfaces

The following code performs the same work 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 means nothing to me. I have searched in different places, but I haven't got 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, onclicklistener () is the interface mentioned in the Android document. Now we are instantiating an interface. Don't we just implement the interface? Please help me understand this

resolvent:

The new onclicklistner() {does not instantiate an interface. It declares an anonymous inner class. It is basically an anonymous class (the class that implements the interface onclicklistner), and it has no name

Start with documentation:

Anonymous class expressions contain the following:

>New operator > name of the interface to be implemented or the class to be extended. In this example, the anonymous class is implementing the onclicklistner interface. > parentheses, which contain the parameters of the constructor, just like the ordinary class instance creation expression. Note: in the case of implementing the interface, there is no constructor, so you use a pair of empty parentheses, just like in this example. > a body, More specifically, method declarations are allowed in the body, but statements are not

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>