0

What does this code mean here:

private ActionListener doGreeting = new ActionListener {
            public void actionPerformed(ActionEvent e) {
               myGreetingField.setText("Hello");
            }
    };

I read somewhere that it is a form of callback but I don't understand what it means. Can someone please explain this and/or provide some sources where it explains it in detail?

EDIT: My reason for asking this question is to understand what this means in Android Studio:

sumButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v)
            {
                String a = et1.getText().toString();
                String b = et2.getText().toString();
                int sum = Integer.parseInt(a) + Integer.parseInt(b);
                Toast.makeText(getApplicationContext(), String.valueOf(sum), Toast.LENGTH_LONG).show();
            }
        });

where we have this format: function1(new Class.function2(){...}); The code above even has another function inside fucntion2 (onClick is inside OnClickListner). Can Someone please clear this up?

Ak01
  • 362
  • 3
  • 19

4 Answers4

2

This is called an anonymous class

It is often used when you need to pass a class that implements an interface.

Edit :

sumButton.setOnClickListener(new View.OnClickListener(){...});

The ... defines what your application should do when the button is clicked.

Degravef
  • 120
  • 8
1

Degravef's answer above has it spot-on. You are, within a single expression, creating a new instance of a class and specifying methods for that class instance. In the first example of your original post, that new class (modified ...) class instance will be assigned as the value of the variable ActionListener, and it will magically have an actionPerformed method which will execute the statements shown. In the second example, it is passed as a the first argument of a call to the setOnClickListener method, and its onClick method will likewise be as shown.

This is just for brevity and convenience: these are "one-off customizations of object instances, intended to be used (only) right here," and Java lets you get straight to the point.

Mike Robinson
  • 8,490
  • 5
  • 28
  • 41
0

I guess you are referring to Anonymous Inner Classes, check this

Basically you want to evaluate function onClick() sometime in future, when you have the View object, but during that time you may not have et1 and et2 object.

BHAWANI SINGH
  • 729
  • 4
  • 8
0

It is an example of Anonymous Inner Class in Java. This answer should give you clear idea - Callback in Java