Java抽象類與接口區(qū)別詳解
很多常見的面試題都會出諸如抽象類和接口有什么區(qū)別,什么情況下會使用抽象類和什么情況你會使用接口這樣的問題。本文我們將仔細討論這些話題。
在討論它們之間的不同點之前,我們先看看抽象類、接口各自的特性。
抽象類
抽象類是用來捕捉子類的通用特性的 。它不能被實例化,只能被用作子類的超類。抽象類是被用來創(chuàng)建繼承層級里子類的模板。以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}
當(dāng)HttpServlet類繼承GenericServlet時,它提供了service方法的實現(xiàn):
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}
接口
接口是抽象方法的集合。如果一個類實現(xiàn)了某個接口,那么它就繼承了這個接口的抽象方法。這就像契約模式,如果實現(xiàn)了這個接口,那么就必須確保使用這些方法。接口只是一種形式,接口自身不能做任何事情。以Externalizable接口為例:
public interface Externalizable extends Serializable { void writeExternal(ObjectOutput out) throws IOException; void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;}
當(dāng)你實現(xiàn)這個接口時,你就需要實現(xiàn)上面的兩個方法:
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); }}
抽象類和接口的對比

什么時候使用抽象類和接口
如果你擁有一些方法并且想讓它們中的一些有默認實現(xiàn),那么使用抽象類吧。 如果你想實現(xiàn)多重繼承,那么你必須使用接口。由于Java不支持多繼承,子類不能夠繼承多個類,但可以實現(xiàn)多個接口。因此你就可以使用接口來解決它。 如果基本功能在不斷改變,那么就需要使用抽象類。如果不斷改變基本功能并且使用接口,那么就需要改變所有實現(xiàn)了該接口的類。以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. IntelliJ IDEA設(shè)置自動提示功能快捷鍵的方法2. PHP程序員簡單的開展服務(wù)治理架構(gòu)操作詳解(二)3. PHP如何開啟Opcache功能提升程序處理效率4. Python3 json模塊之編碼解碼方法講解5. android H5本地緩存加載優(yōu)化的實戰(zhàn)6. JavaScript創(chuàng)建表格的方法7. 從Python的字符串中剝離所有非數(shù)字字符(“。”除外)8. ASP.NET MVC使用jQuery ui的progressbar實現(xiàn)進度條9. 詳解如何使用Net將HTML簡歷導(dǎo)出為PDF格式10. python新手學(xué)習(xí)使用庫

網(wǎng)公網(wǎng)安備