16.为什么要用抽象类

  • 当我们把父类定义为抽象类,而把子类定义为抽象函数的话
  • 当我们无法写出通用函数的时候,避免失误出现
 
  1. abstract classPrinter{
  2. void open(){
  3. System.out.println("open");
  4. }
  5. void close(){
  6. System.out.println("close");
  7. }
  8. abstract void print();
  9. }
 
  1. //该打印机为喷墨打印机
  2. classHPPrinter extends Printer{
  3. void print(){
  4. System.out.println("使用喷墨打印机打印");
  5. }
  6. }
 
  1. //该打印机为针式打印机
  2. classCanonPrinter extends Printer{
  3. void print(){
  4. System.out.println("使用针式打印机");
  5. }
  6. }
 
  1. classTest{
  2. publicstaticvoid main(String args []){
  3. Printer p1 =newHPPrinter();
  4. p1.open();
  5. p1.print();
  6. p1.close();
  7. Printer p2 =newCanonPrinter();
  8. p2.open();
  9. p2.print();
  10. p2.close();
  11. }
  12. }
 
结果:
D:\work\src>javac *.java
 
D:\work\src>java Test
open
使用喷墨打印机打印
close
open
使用针式打印机
close
 





posted @ 2016-08-28 17:20  ArronEve  阅读(166)  评论(0编辑  收藏  举报