16.为什么要用抽象类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
 





以上是关于16.为什么要用抽象类的主要内容,如果未能解决你的问题,请参考以下文章

抽象类接口

不明白java中的泛型和抽象类有啥区别,感觉他们作用一样啊,为啥要用2种方法呢

JAVA面向对象 - 抽象类接口

16-抽象类及接口

蓝鸥Unity开发基础二——课时16 抽象类

OO面向对象——抽象类abstrac