Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programming convention on Anonymous Class vs Implementing Interface

From the android development perspective, while you are programming which way do you prefer to implement for listener? Or which way do you think is the best for readable code? I gave two example about these things but think more complex classes such as which has more than one Listener:)

First example which is an Anonymous Class:

public class SenderReceiverActivity extends Activity {

Button cancelButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sending);
    cancelButton = (Button) findViewById(R.id.button1);
    cancelButton.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

        }
    });
}}

Second example which is implementing interface :

public class SenderReceiverActivity extends Activity implements OnClickListener {

Button cancelButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sending);
    cancelButton = (Button) findViewById(R.id.button1);
    cancelButton.setOnClickListener(this);
}

public void onClick(View v) {

}
}
like image 570
Omer Faruk Celebi Avatar asked May 30 '12 06:05

Omer Faruk Celebi


People also ask

Can Anonymous classes be implemented an interface?

A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time.

What is the purpose of anonymous class in Java?

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

What is meant by an anonymous class?

A nested class that doesn't have any name is known as an anonymous class. An anonymous class must be defined inside another class. Hence, it is also known as an anonymous inner class. Its syntax is: class outerClass { // defining anonymous class object1 = new Type(parameterList) { // body of the anonymous class }; }


2 Answers

if you have single button then first approch is right because there are no any complexity in your code but when you have many button then second is more clear ,just one onClick method for many buttons and check id of button using v.getId()

But there are no any change in functionality both are identical.

like image 55
Samir Mangroliya Avatar answered Oct 05 '22 23:10

Samir Mangroliya


I think 2nd approch is good as

1- you can handle multiple Views click at one place...

2- it make code shorter and easy to read..

3- it is easy in maintenance.

4- if you are using the Base Activity like concept in your project then it is also useful.

like image 32
Dheeresh Singh Avatar answered Oct 06 '22 01:10

Dheeresh Singh