-1

Since object creation of an interface is not allowed in java. Going through the button event creation code, i passed through this:

       View. OnClickListener ocl=new   View. OnClickListener ();

As per Android documentation onClickListener is an interface then how can we create its object. Object creation of interface is not allowed but the keyword new clearly does that. How is it possible? Please excuse any mistakes, i am new to Android development.

sociopath
  • 79
  • 1
  • 6

4 Answers4

1

In simple words..

The instance you create is of anonymous class that implements View.OnClickListener, in the brackets.

SRB Bans
  • 3,096
  • 1
  • 10
  • 21
0

You don't. The system does. You just provide the implementation of the interface.

pepan
  • 678
  • 6
  • 11
  • As per JAVA, you cannot create an object of an interface. So how could this happen/allowed- :new View. OnClickListener () [object creation] – sociopath Jul 15 '17 at 12:58
0

If you want to write one ClickListener to use for several view's click event, the try this:

    View.OnClickListener onClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // write your code here
        }
    };

Now you can set onClick to your view's ClickListener:

btn.setOnClickListener(onclick);
SiSa
  • 2,594
  • 1
  • 15
  • 33
0

Whenever an interface is needed, you need to provide an implementation of this interface. It means that the class requiring an interface does not care of the class of the implementation, it just cares to know that it can use the instance it received in a specific way and that the instance can achieve what has been asked through its implementation.

Then you have two options which are creating a class that implements the View.OnClickListener interface or instantiate an anonymous class.

Option 1:

public class ClickListenerImpl implements View.OnClickListener
{   
    @Override
    public void onClick(View view) { /* logic */ }
}

and then

View.OnClickListener ocl = new ClickListenerImpl();

Option 2:

View.OnClickListener ocl = new View.OnClickListener()
{
    @Override
    public void onClick(View view) { /* logic */ }
};
Maaaatt
  • 429
  • 4
  • 14