原文链接: javacodegeeks 翻译: ImportNew.com - jessenpan
在看jdk源码时发现,ArrayList和HashSet方法分别继承了抽象类AbstractList、AbstractSet ,为什么要设置抽象类,而不直接实现相应的接口?
因为接口无法实现方法(jdk1.8已可在接口实现默认方法),抽象类可实现公共的方法给子类继承;实现接口需实现接口定义的所有方法,抽象类只重载你需要的方法,代码更加简洁。
关于抽象类和接口区别,可看如下介绍 。在讨论它们之间的不同点之前,我们先看看抽象类、接口各自的特性。
抽象类是用来捕捉子类的通用特性的 。它不能被实例化,只能被用作子类的超类。抽象类是被用来创建继承层级里子类的模板。以JDK中的GenericServlet为例:
1 2 3 4 5 6 7 8 9 public abstract class GenericServlet implements Servlet, ServletConfig, Serializable { // abstract method abstract void service(ServletRequest req, ServletResponse res); void init() { // Its implementation } // other method related to Servlet }当HttpServlet类继承GenericServlet时,它提供了service方法的实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public class HttpServlet extends GenericServlet { void service(ServletRequest req, ServletResponse res) { // implementation } protected void doGet(HttpServletRequest req, HttpServletResponse resp) { // Implementation } protected void doPost(HttpServletRequest req, HttpServletResponse resp) { // Implementation } // some other methods related to HttpServlet }接口是抽象方法的集合。如果一个类实现了某个接口,那么它就继承了这个接口的抽象方法。这就像契约模式,如果实现了这个接口,那么就必须确保使用这些方法。接口只是一种形式,接口自身不能做任何事情。以Externalizable接口为例:
1 2 3 4 5 6 public interface Externalizable extends Serializable { void writeExternal(ObjectOutput out) throws IOException; void readExternal(ObjectInput in) throws IOException, ClassNotFoundException; }当你实现这个接口时,你就需要实现上面的两个方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public class Employee implements Externalizable { int employeeId; String employeeName; @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { employeeId = in.readInt(); employeeName = (String) in.readObject(); } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(employeeId); out.writeObject(employeeName); } }Oracle已经开始尝试向接口中引入默认方法和静态方法,以此来减少抽象类和接口之间的差异。现在,我们可以为接口提供默认实现的方法了并且不用强制子类来实现它。这类内容我将在下篇博客进行阐述。
转载于:https://www.cnblogs.com/catluo/p/10803970.html
