用抽象類來實現接口的意義


抽象類和接口都是java中用來實現多態的方法,在此主要說明為什么會用抽象類來實現接口,因此對兩者之間的異同就不介紹了。

在java一般的用法中,如果要用普通類來實現接口,則必須實現該接口中的所有方法,這樣就會導致需要實現多余的方法;

采用抽象類來實現方法,可以實現該接口中的部分方法,而且當其他類繼承該抽象類時,只需要實現抽象類中未實現的方法即可。

例:

  抽象類B只實現了接口A中的方法a、b,

  當類C繼承類B時,只需要實現B中為實現的接口c即可。

  一般情況下,類C中的方法a、b都是調用父類B的方法a、b。

-------------------------------------------- 

另外:

  接口種沒有構造方法,抽象類可以有構造方法。

例:

 

 1 package cn.tedu;
 2 
 3 public class test {
 4 
 5     public static void main(String[] args) {
 6         AProduct a = new AProduct("呵呵");
 7         a.print();
 8         a.printBefore();
 9         
10         System.out.println("=========");
11         BProduct b = new BProduct("哈哈");
12         b.print();
13         b.printBefore();
14         
15         
16     }
17 }
18 
19 interface IProduct {
20     void print(); // 這是要暴露的方法
21 }
22 
23 abstract class AbstractProduct implements IProduct {
24     public AbstractProduct() {
25         // TODO Auto-generated constructor stub
26     }
27 
28     protected void printBefore() {
29         System.out.println("before print"); // 這里所公共的實現
30     }
31 }
32 
33 class AProduct extends AbstractProduct {
34     private String name;
35 
36     public AProduct(String name) {
37         this.name = name;
38     }
39 
40     @Override
41     public void print() {
42         this.printBefore();
43         System.out.println("print A >>>" + name);
44     }
45 }
46 
47 class BProduct extends AbstractProduct {
48     private String name;
49 
50     public BProduct(String name) {
51         this.name = name;
52     }
53 
54     @Override
55     public void print() {
56         this.printBefore();
57         System.out.println("print B >>>" + name);
58     }
59 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM