首页 > 技术文章 > 用抽象类来实现接口的意义

pxffly 2017-09-20 21:25 原文

抽象类和接口都是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 }

 

推荐阅读