0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

そういえばしれっと匿名クラス登場してたじゃんか

0
Posted at

応プロでそういや登場してましたね。

button.addActionListener(
  new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent event){
      /* ここにボタンが押されたときの処理を記述 */
    }
  }
);

これについて。

匿名クラス

匿名クラスって言って、その場でさっくりクラスを作成できる書き方がある。

例えば、こんなインタフェースを設計してみる。

SampleInterface.java
interface SampleInterface{
    public void sampleMethod();
}

じゃ、コレの匿名クラスを生成してみる。

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

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

こんなして使える。

やってることとしては

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

これと同じ。
わざわざ別ファイルでインターフェースを実装したクラスを作る手間が省ける。

何に使う?

これを使うと、他のクラスに処理そのものをブチ込める。

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!!!! :-)

こんな感じ。

Javaを使ったフレームワークなんかだとしょっちゅう見かける。
ボタンの処理をしているクラスを変更することなく自分のしたい処理を差し込めるから、フレームワークの便利な処理をそのままにできるってこと。
Androidでもボタン押したときにやる処理なんかはこのパターンだし。


以上、リスナーパターンってやつのお話でした。

0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?