现在的位置: 首页 > 综合 > 正文

Java中接口与抽象类的区别

2019年01月15日 ⁄ 综合 ⁄ 共 1837字 ⁄ 字号 评论关闭

1、概念:

抽象类(abstract class):声明方法的存在但不去实现它的类叫做抽象类。抽象类中可以有实现了的方法,也可以没有实现了的方法;抽象类中可以没有抽象的方法,但有抽象方法的类一定是抽象类。抽象类与普通类最大的区别是它不能被直接实例化,只能通过子类间接实例化。

接口(interface):是抽象类的变体。其中所有的方法都是抽象类,且只能定义static final成员变量。

 

2、区别

两者的相同点:

(1)两者都是抽象类,都不能实例化。

(2)interface实现类及abstract class的子类都必须要实现已经声明的抽象方法。

 

两者的不同点:

(1)一个类可以实现(implements)多个interface,但一个类只能继承(extends)一个abstract class

(2)interface强调特定功能的实现,具有哪些功能;而abstract class强调所属关系。

(3)尽管interface实现类及abstract class的子类都必须要实现相应的抽象方法,但实现的形式不同。interface中的每一个方法都是抽象方法,都只是声明的(declaration, 没有方法体),实现类必须要实现。而abstract class的子类可以有选择地实现(只实现其中的抽象方法;覆盖其中已实现了的方法;二者均实现)。

(4)interface是完全抽象的,只能声明方法,而且只能声明public的方法,不能声明private及protected的方法,不能定义方法体,也不能声明实例变量。

 

abstract class在interface及Class中起到了承上启下的作用。一方面,abstract class是抽象的,可以声明抽象方法,以规范子类必须实现的功能;另一方面,它又可以定义缺省的方法体,供子类直接使用或覆盖。另外,它还可以定义自己的实例变量,以供子类通过继承来使用。

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

Example from the JRE: LinkedList is
both a 
List and
Deque.
These interfaces define the behaviour of the class. They do not provide any implementation details. While abstract classes 
couldprovide
some.

为什么Java中采用多接口而没有多继承:

接口只定义了你做什么,而不关心你怎么做;

如果是多继承,有可能两个类定义的两个方法是做同一件事情的,那么他们的子类就无法选择到底去用哪一个。

抱歉!评论已关闭.