你什么时候用abstract class,什么时候用interface”。所以在这篇文章中,我们将讨论这个话题。
abstract class
interface
在讨论它们之间的差异之前,让我们先来看看它的介绍。
Abstract classes是为了捕捉子类的共同特征而创建的。它不能被实例化,它只能被它的子类用作超类。抽象类用于为其子类在层次结构中创建模板。让我们以JDK类为例GenericServlet
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 扩展 Generic servlet 时,它提供了 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 }
接口是抽象方法的集合。一个类实现了一个接口,从而继承abstract methods了接口的。所以它是一种签订合同,你同意如果你实现了这个接口,那么你必须使用它的方法。它只是一个模式,它本身不能做任何事情。 让我们以可外部化接口为例。
abstract methods
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); } }
Oracle 试图通过在接口中引入默认方法和静态方法的概念来弥合抽象类和接口之间的鸿沟。所以现在我们可以在接口中提供方法的默认实现,而不会强制类来实现它。我将在下一篇文章中介绍这些主题。
原文链接:https://codingdict.com/