Lambda Expressions for Abstract Classes

后端 未结 3 1454
梦如初夏
梦如初夏 2020-11-30 03:03

I have an abstract class with one abstract method. How can I use lambda expressions to instantiate it. It cannot be made into an interface because it extends a class.

3条回答
  •  没有蜡笔的小新
    2020-11-30 03:58

    In the meantime, we now have default implementations in interfaces. I was in a similar situation, tried with an abstract class. Switched to an interface with 2 methods, one of them having a default implementation. Java identifies the interface as having a single abstract method and I can use the lambda syntax for passing implementations of the interface as arguments.

    The downside is that someone could override the method which has a default implementation if they really insist, by explicitly implementing the interface in some (anonymous or not) class. And you can't limit that because on interfaces all methods are public. Depending on your situation, that might not be a big deal.

提交回复
热议问题