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

浙公网安备 33010602011771号