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

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

问题描述

在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?

推荐答案

不总是:


  • 一个类可以只扩展一个类

  • 一个类可以实现多个界面

  • a class can extend only one class
  • a class can implement more than one 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).

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

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