歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 源碼詳解Java接口和抽象類的區別

源碼詳解Java接口和抽象類的區別

日期:2017/3/1 10:07:43   编辑:Linux編程

Java基礎之基礎,抽象類和接口的區別。要是還不能很清晰的給別人講述這兩者之間的區別,建議自己動手寫寫代碼,就會有所領悟了。

1.抽象類

  1. public abstract class testAbstractClass {
  2. //抽象類是可以有私有方法或私有變量
  3. private int TEST_NUM;
  4. public abstract int testMethod();
  5. public int test2Method() {
  6. return 0;
  7. }
  8. //私有方法
  9. private int test3Method() {
  10. return 0;
  11. }
  12. }

2.接口

  1. public interface testInterface {
  2. //接口是公開的,裡面不能有私有的方法或變量,是用於讓別人使用的
  3. public abstract int testInterface();
  4. public int test2Interface();
  5. }

3.子類繼承抽象類

  1. public class testExtendsAbstractClass extends testAbstractClass{
  2. //繼承抽象類可以有選擇的重寫需要用到的方法,但抽象方法必須實現
  3. @Override
  4. public int testMethod() {
  5. // TODO Auto-generated method stub
  6. return 0;
  7. }
  8. }

4.子類實現接口

  1. public class testImplementsInterface implements testInterface {
  2. //實現接口一定要實現接口定義的所有方法
  3. @Override
  4. public int testInterface() {
  5. // TODO Auto-generated method stub
  6. return 0;
  7. }
  8. @Override
  9. public int test2Interface() {
  10. // TODO Auto-generated method stub
  11. return 0;
  12. }
  13. }

注:以上代碼均為編譯通過

總結:

1.接口是公開的,裡面不能有私有的方法或變量,是用於讓別人使用的;而抽象類是可以有私有方法或私有變量;
2.實現接口一定要實現接口定義的所有方法,而繼承抽象類可以有選擇的重寫需要用到的方法,但抽象方法必須實現;
3.一般應用裡,最頂級的是接口,然後是抽象類實現的接口,最後才是具體類的實現。
4.接口多實現,類單繼承

常見思考問題:

1.抽象類中私有方法或私有變量有什麼作用;
2.接口中抽象方法和一般方法有什麼區別;
3.其他……

Copyright © Linux教程網 All Rights Reserved