Fundamental difference between interface and abstract class in Java 8 [duplicate]

淺唱寂寞╮ 提交于 2019-12-07 10:49:56

问题


Considering that interfaces now can give an implementation to the methods it provides, I cannot properly rationalize the difference between interfaces and abstract classes. Does anyone know how to explain the difference properly?

I was also told that interfaces are somewhat more light-weight compared to abstract classes, performance wise. Can someone confirm this?


回答1:


Interfaces still can't have any state. Interfaces still can't have any final method, which means that any implementation can override all its default methods. And interfaces still can't have any constructor.

You can still implement multiple interfaces, even if they have default methods with the same signature. You can't extend multiple classes (abstract or not).




回答2:


  1. a class may inherit from only one other class, but can implement many interfaces
  2. an interface may not have any fields, expect defining constants, while an abstract class can
  3. an abstract class may define a constructor, while an interface can not

Default methods are restricted to input parameters and method calls. They are stateless in nature. An abstract class may have state. Hence, from the perspective of design, I would suggest to use abstract classes whenever you need code reuse. Reducing code reuse to package scope is a good design principle in my opinion.

Interfaces are perfect to model and communicate the concepts of a package, a library, a domain or an application. They do not rely on implementation details and allow to replace the implementations at will. They support testing and modularization.



来源:https://stackoverflow.com/questions/22855670/fundamental-difference-between-interface-and-abstract-class-in-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!