When to use: Java 8+ interface default method, vs. abstract method

后端 未结 15 1912
闹比i
闹比i 2020-11-22 07:01

Java 8 allows for default implementation of methods in interfaces called Default Methods.

I am confused between when would I use that sort of interface default

15条回答
  •  迷失自我
    2020-11-22 07:19

    Although its an old question let me give my input on it as well.

    1. abstract class: Inside abstract class we can declare instance variables, which are required to the child class

      Interface: Inside interface every variables is always public static and final we cannot declare instance variables

    2. abstract class: Abstract class can talk about state of object

      Interface: Interface can never talk about state of object

    3. abstract class: Inside Abstract class we can declare constructors

      Interface: Inside interface we cannot declare constructors as purpose of
      constructors is to initialize instance variables. So what is the need of constructor there if we cannot have instance variables in interfaces.

    4. abstract class: Inside abstract class we can declare instance and static blocks

      Interface: Interfaces cannot have instance and static blocks.

    5. abstract class: Abstract class cannot refer lambda expression

      Interfaces: Interfaces with single abstract method can refer lambda expression

    6. abstract class: Inside abstract class we can override OBJECT CLASS methods

      Interfaces: We cannot override OBJECT CLASS methods inside interfaces.

    I will end on the note that:

    Default method concepts/static method concepts in interface came just to save implementation classes but not to provide meaningful useful implementation. Default methods/static methods are kind of dummy implementation, "if you want you can use them or you can override them (in case of default methods) in implementation class" Thus saving us from implementing new methods in implementation classes whenever new methods in interfaces are added. Therefore interfaces can never be equal to abstract classes.

提交回复
热议问题