ARP
ARP

Reputation: 613

OnClickListener interface in Android

I am new to programming, I have very basic knowledge in android. As I learned in java that an Interface cannot be instantiated And that new is a keyword in Java that indicates creating an instance. I came across following code in Android:

public class MyActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);

    setContentView(R.layout.mylayout);
    findViewById(R.id.button1).setOnClickListener(mButton1_OnClickListener);
  }  

  //On click listener for button1
  final OnClickListener mButton1_OnClickListener = new OnClickListener() {
    public void onClick(final View v) {
        //Inform the user the button has been clicked
        Toast.makeText(this, "Button1 clicked.", Toast.LENGTH_SHORT).show();               
    }
  };
}

Above code OnClickListener is a public interface and onClick(final View v) is an abstract method, Here goes my question: OnClickListener being an interface, how is possible to create an instance of it by using the new keyword in the example above?

Upvotes: 5

Views: 3236

Answers (3)

ARP
ARP

Reputation: 613

After long study am able to get clarification on anonymous class.Basically Anonymous stands for NO NAME,So the class with out any name is an Anonymous class . Ex:

  final OnClickListener mButton1_OnClickListener = new OnClickListener() {
        public void onClick(final View v) {
            //Inform the user the button has been clicked
            Toast.makeText(this, "Button1 clicked.", Toast.LENGTH_SHORT).show();               
        }
      };

Lets take an example of above code .It is an anonymous implementation , where mButton1_OnClickListener is an object of anonymous class and this anonymous class implementing OnClickListener interface. Similer example - How can an anonymous class use "extends" or "implements"?

Upvotes: 1

rupesh
rupesh

Reputation: 2891

Here you are not instantiating an interface you are doing by Anonymous inner class.Your are not creating the object of the interface .you are creating this for the Anonymous class which is you gonna create in next step inside {Anonymous inner class};.If want to know more details of this you have to through Anonymous inner class.

Check it out below links:

http://c2.com/cgi/wiki?AnonymousInnerClass

http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

Upvotes: 5

Abhishek V
Abhishek V

Reputation: 12536

It is called anonymous inner class. That concept is entirely different.Behind the scenes, The compiler automatically creates a new class which implements that onClickListenerinterface.

This below link has detailed answer for your question.

Creating object from OnClickListener interface

Upvotes: 1

Related Questions