使用“抽象方法”有什么意义?抽象类不能被实例化,那么抽象方法呢?他们只是在这里说“你必须实现我”,如果我们忘记它们,编译器会抛出错误吗?
还有别的意思吗?我也读过一些关于“我们不必重写相同的代码”的内容,但是在抽象类中,我们只“声明”了抽象方法,所以我们将不得不在子类中重写代码。
你能帮我多理解一下吗?我检查了有关“抽象类/方法”的其他主题,但没有找到答案。
最佳答案
假设您有三台打印机需要为其编写驱动程序:Lexmark
、Canon
和 HP
。
所有三台打印机都有 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/