0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

関数型インタフェースは抽象メソッドが1つだけであれば、フィールドやdefaultメソッドを持っても問題ないことを知った

Posted at

関数型インタフェースのことを「抽象メソッドを1つだけ持つインタフェース」と認識していたため、フィールドやdefaultメソッドも定義できないと勝手に思い込んでいたが、試してみるとフィールドやdefaultメソッドを定義しても問題ないことが分かった。

Test.java
package org.example;

public interface Test {
    void test();
    int num = 0;
    default void a() {
        System.out.println("a");
    }
}
Main.java
package org.example;

public class Main {
    public static void main(String[] args) {
        Test t = () -> System.out.println("test");
        t.test();
        t.a();
        System.out.println(t.num);
    }
}
出力結果
test
a
0

しかし、あえて抽象メソッドを1つのみ定義することで効果を発揮していると思われる関数型インタフェースに、わざわざフィールドやdefaultメソッドはいらないだろうと感じた。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?