0

When doing android development, I often encounter codes like:

timer = new CountDownTimer(counter, 1000) {
                public void onTick(long remainingTimeMillis) {
                    counter = remainingTimeMillis;
                    displayCount(counter);
                }
                public void onFinish() {
                    displayCount(0);
                    counter = 0;
                    timer = null;
                    beep.start();
                }
            };

or

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String s = (String) v.getTag();
                int duration = Toast.LENGTH_SHORT;
                Toast toast = Toast.makeText(context, s, duration);
                toast.show();

            }
        });

I've never seen such use in Java in other areas, could somebody explain what it means when calling a constructor and then define some other methods in it, which is like defining a class for me. And usually what are the circumstances where we need to use this kind of structure? Thanks a lot.

J Freebird
  • 3,664
  • 7
  • 46
  • 81

3 Answers3

3

This is called anonymous class. In parenthesis after constructor, you create a class extending mentioned class or implementing mentioned interface, override it's method(s) and/or define new methods and fields, and then create an instance of this new class.

This new class has no name, object cannot be referenced. It is often used when you need to implement abstract methods of some class/interface, create single object and pass this object as an argument.

For example, OnClickListener interface has an abstract method onClick() which is used as callback when click event is fired. If there were no anonymous classes, you need, first, to declare class implementing given interface, then create object of it, and only then pass it as an argument to setOnClickListener method with explicit cast. Using anonymous class, you can write it with less code and more readability.

Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67
2
button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String s = (String) v.getTag();
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, s, duration);
            toast.show();

        }
    });

Here you have a annonymous inner class. The class implements the interface OnClickListener and you implement the method onClick.

You could have your Activity class implement OnClickListener and the

 button.setOnClickListener(this); // this refers to the Activity class

And then override onClick in Activity

 @Override
 public void onClick(View v) {
 switch(v.getId)
 {
     case R.id.button1 :
     break; 
 }

 }

If you have more buttons i prefer the above method.

How are Anonymous (inner) classes used in Java?

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

and this

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

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • Thanks for your answer. But here I'm still quite confused about the interface stuff, can you just create a new interface using new and pass the interface as an argument? I think we can only pass in objects. – J Freebird Apr 15 '14 at 20:40
  • @JFreebird you implement the interface. `new View.OnClickListener() {` You have annonymous inner class which implements the interface `OnClickListener`. I think you are confused by the syntax. Check this http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html – Raghunandan Apr 16 '14 at 04:01
1

In the examples you've quoted, an anonymous object of the mentioned class is being created and passed to the method as an expected argument. Thing to note here is that some of the methods of the class are overridden. This is not exclusive to android though. This is commonly used for creating anonymous objects of interfaces and/or abstract class to pass to a method as an argument. Alternative to this syntax would be create a new class implementing or extending the interface or abstract class and then creating a new object of this class and passing it to the required method. And thus, the quoted example can be called a short and neat method to tackle this case.