LoginSignup
31
29

More than 5 years have passed since last update.

JAVA インナークラス・匿名クラス

Last updated at Posted at 2016-01-19

匿名クラスとは
あるメソッドの中で一回しか使わない、つまり
「その場で使い捨てる」クラスを作りたい場合のためにある。

  • 匿名クラスの特異性_________________________________
  • 普通のクラスやメンバクラスは、classキーワードでまず「宣言」し、 その後newで「利用」しますが、 匿名クラスは「宣言と利用」を同時に行います。
    _________________________________________________________

■匿名クラスの宣言兼利用
new 匿名クラスの親クラス指定(){
匿名クラスの内容(メンバ)定義
}

無名クラスは「new インターフェイス名() { …実装… }」の形式で表します。

▪️Test105.java


public class Test105 {
    public static void main(String[] args) {
        Printable p = new Printable() {
            public void print() {
                System.out.println("TEST");
                System.out.println("TEST2");
            }
        };
        p.print();

        Printable2 p2 = new Printable2() {
            public void print2() {
                System.out.println("TEST3");
            }
        };
        p2.print2();
    }
}

▪️Printable.java

public interface Printable {
    void print();
}

▪️Printable2.java

public interface Printable2 {
    void print2();
}

▪️Test105.java 実行結果
TEST
TEST2
TEST3

31
29
0

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
31
29