[JAVA] Speaking of which, an anonymous class has appeared.

No, it appeared as a professional.

button.addActionListener(
  new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent event){
      /*Describe the processing when the button is pressed here*/
    }
  }
);

about this.

Anonymous class

There is a way to write ** anonymous class ** so that you can create a class on the spot.

For example, try designing such an interface.

SampleInterface.java


interface SampleInterface{
    public void sampleMethod();
}

Now, let's generate this ** anonymous class **.

SampleInterface sample = new SampleInterface(){
    @Override
    public void sampleMethod(){
        System.out.println("Hello :-) ");
    }
}

sample.sampleMethod();
// >>> Hello :-) 

You can use it like this.

What I'm doing

ExampleClass.java


class ExampleClass implements SampleInterface{
    @Override
    public void sampleMethod(){
        System.out.println("Hello :-) ");
    }
}
SampleInterface sample = new ExampleClass();
sample.sampleMethod();
// >>> Hello :-) 

Same as this. You can save the trouble of creating a class that implements the interface in a separate file.

What do you use it for?

With this, you can put the processing itself into other classes.

SampleClass.java


class SampleClass{
    private SampleInterface sampleInterface;

    public SampleClass(SampleInterface sampleInterface){
        this.sampleInterface = sampleInterface;
    }

    public void callInterfaceMethod(){
        sampleInterface.sampleMethod();
    }
}
SampleClass sample = new SampleClass(
    new SampleInterface(){
        @Override
        public void sampleMethod(){
            System.out.println("Hellooooooo!!!! :-) ");
        }
    }
);

sample.callInterfaceMethod()
// >>> Hellooooooo!!!! :-)

Like this.

I often see frameworks that use Java. Since you can insert the processing you want without changing the class that processes the button, you can leave the convenient processing of the framework as it is. Even on Android, this pattern is what you do when you press a button.


That's all for the ** listener pattern **.

Recommended Posts

Speaking of which, an anonymous class has appeared.
Anonymous class (anonymous class)
Java anonymous class