java - 使用抽象方法有什么意义?

标签 java abstract-class

使用“抽象方法”有什么意义?抽象类不能被实例化,那么抽象方法呢?他们只是在这里说“你必须实现我”,如果我们忘记它们,编译器会抛出错误吗?

还有别的意思吗?我也读过一些关于“我们不必重写相同的代码”的内容,但是在抽象类中,我们只“声明”了抽象方法,所以我们将不得不在子类中重写代码。

你能帮我多理解一下吗?我检查了有关“抽象类/方法”的其他主题,但没有找到答案。

最佳答案

假设您有三台打印机需要为其编写驱动程序:LexmarkCanonHP

所有三台打印机都有 print()getSystemResource() 方法。

但是,print() 对于每台打印机都是不同的,而 getSystemResource() 对于所有三台打印机都是一样的。您还有另一个顾虑,您想应用多态性。

由于三台打印机的getSystemResource()都是一样的,你可以把它推到父类(super class)去实现,让子类实现print() .在 Java 中,这是通过在父类(super class)中使 print() 抽象来完成的。注意:在类中将方法抽象化时,类本身也需要抽象化。

public abstract class Printer{
  public void getSystemResource(){
     // real implementation of getting system resources
  }
  
  public abstract void print();
}

public class Canon extends Printer{
  public void print(){
    // here you will provide the implementation of print pertaining to Canon
  }
}

public class HP extends Printer{
  public void print(){
    // here you will provide the implementation of print pertaining to HP
  }
}

public class Lexmark extends Printer{
  public void print(){
    // here you will provide the implementation of print pertaining to Lexmark
  }
}

请注意,HP、Canon 和 Lexmark 类不提供 getSystemResource() 的实现。

最后,在您的主课中,您可以执行以下操作:

public static void main(String args[]){
  Printer printer = new HP();
  printer.getSystemResource();
  printer.print();
}

关于java - 使用抽象方法有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8394252/

相关文章:

android - 继承和泛型 java android

c++ - 抽象类可以继承自 "normal"类吗?

c++ - 这个派生类是如何抽象的呢?

java - 如何从我的 war 中访问文本文件

java - 接口(interface)的所有方法都是抽象的吗?

java - 在同一 JVM 中运行 Apache MINA 和 Netty

java - JAVA如何增加word文件中表格的列宽

c# - 实现派生类接口(interface)方法的抽象基类

java - 在将布局膨胀对象添加到 View 时设置其重力

java - 在JAVA中发出多个http请求的快速异步方法