gpt4 book ai didi

java - 抽象类是否/可以取代接口(interface)?

转载 作者:IT老高 更新时间:2023-10-28 20:42:56 25 4
gpt4 key购买 nike

在 Java 中,您可以创建一个只包含抽象方法的抽象类。另一方面,您可以创建一个声明相同方法的接口(interface)。既然如此,可以用抽象类代替接口(interface)吗?

最佳答案

并非总是如此:

  • 一个类只能扩展一个
  • 一个类可以实现多个接口(interface)

Sun docs进行更详细的比较:

Abstract Classes versus Interfaces

Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.

Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.

By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods).

关于java - 抽象类是否/可以取代接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2124951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com