java抽象类和接口有什么区别?项目中怎么去使用它们?

2020-08-05 10:44发布

4条回答
水默
2021-12-13 11:27

抽象类

抽象类是用来捕捉子类的通用特性的 。它不能被实例化,只能被用作子类的超类。抽象类是被用来创建继承层级里子类的模板。

以JDK中的GenericServlet为例:

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方法的实现:

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接口为例:

public interface Externalizable extends Serializable {

void writeExternal(ObjectOutput out) throws IOException;

void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;

}

当你实现这个接口时,你就需要实现上面的两个方法:

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

}

}


一周热门 更多>