抽象类可以/可以代替接口吗? [英] Do/can abstract classes replace interfaces?

查看:37
本文介绍了抽象类可以/可以代替接口吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,您可以创建一个仅包含抽象方法的抽象类.另一方面,您可以创建一个声明相同方法的接口.既然如此,能不能用抽象类代替接口?

In Java, you can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. That being the case, can you use abstract classes instead of interfaces?

推荐答案

不总是:

  • 一个类可以扩展一个
  • 一个类可以实现多个接口

Sun docs 做了更详细的对比:

抽象类与接口

与接口不同,抽象类可以包含非静态和最终的字段,并且可以包含已实现的方法.这种抽象类类似于接口,只是它们提供了部分实现,将它留给子类来完成实现.如果抽象类只包含抽象方法声明,则应将其声明为接口.

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.

多个接口可以由类层次结构中任何位置的类实现,无论它们是否以任何方式相互关联.例如,想想 Comparable 或 Cloneable.

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).

这篇关于抽象类可以/可以代替接口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆