Java中抽象类和接口的区别

抽象类和接口在系统设计中起着至关重要的作用,合理的运用,能够使我们设计的系统维护性、扩展性更强

下面说说我对抽象类和接口的理解

 

翻阅ORACLE官方文档,对于接口和抽象类是这么定义的:

接口: https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html

In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces. 

Note that the method signatures have no braces and are terminated with a semicolon.

上面有几个需要注意的地方:

1)a reference type, similar to a class,说明接口不是类,而是一种引用类型

2)contain only constants, method signatures, default methods, static methods, and nested types,接口只能包含常量(基本数据类型为static final)、方法申明,默认方法(Java 8)、静态方法、嵌入类型

3)cannot be instantiated,接口没法实例化,但是可以声明(然后让声明的引用指向已实例化的实现了该接口的对象)

4)only be implemented by classes or extended by other interfaces,接口只能被实现或者被其他接口继承

5)method signatures have no braces,接口中的方法声明不需要函数体,即不需要花括号,而且权限类型必须是public

 

抽象类:https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html

An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.

Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods. With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public. In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.

同样,需要咬文嚼字一下:

1)An abstract class,抽象类是类,不是接口,并用abstract修饰

2)not include method,它可以包含或者不包含抽象方法

3)cannot be instantiated,抽象类也不能实例化,只能作为父类

3)can declare fields that are not static and final, and define public, protected, and private concrete methods,抽象类除了一点约束外(用abstract修饰、不能实例化),其它定义上的操作与普通类一样,定义的域(一般是方法或者属性)可以为静态、非静态,final、非final、访问权限可以使public、protected、private

 4)whereas you can implement any number of interfaces,不论是抽象类还是费抽象类,你都可以实现多个接口

 

上面是对官方文档中定义的一点理解,下面用更通俗的方式讲一下区别:

抽象类遵循类的思想,即它定义的是 “是什么(who)”,而接口定义的是 “做什么(what)”

比如男同学、女同学,这两个类,他们的抽象是学生

人可以吃东西,狗也可以吃东西,所以可以把吃这个动作定义成一个接口,然后让其它类去实现

所以当你关注一个事物的本质(归属问题),考虑使用抽象类,当你关注一个共有的动作或者操作时,考虑使用接口

抽象类的功能要比接口的功能强大,但是抽象类的代价比较高,因为在Java中,一个类只能继承一个类,所以设计时必须做好类的抽象,定义好子类的一些共性

 

posted @ 2016-04-29 10:56  chuenfai  阅读(144)  评论(0编辑  收藏  举报