gpt4 book ai didi

Java 方法 : @Override vs abstract

转载 作者:行者123 更新时间:2023-11-29 10:04:06 28 4
gpt4 key购买 nike

从抽象父类中声明方法时,使用以下一种样式相对于另一种样式的优点/缺点是什么:

选项 1:

父类:

protected Object retrieve(String id, Object model){
return null;
}

子类:

@Override
public String retrieve(Object model) {
if (model instanceof Car)
// ... somehow get id ...
return getInfo(id, (Car)model);
return null;
}

或者...

选项 2:

父类:

protected abstract Object retrieve(String id, Object model);

子类:

public String retrieve(String id, Object model) {
if (model instanceof Car)
return getInfo(id, (Car)model);
return null;
}

最佳答案

使用抽象类,可以保证子类将覆盖抽象方法(如果有的话)(或者它本身是抽象的)。它们也不能被实例化,这很重要,因为它们缺少功能(抽象方法)。

另见 http://wiki.answers.com/Q/Use_of_abstract_class_in_java :

An Abstract class is similar to an interface. You cannot instantiate them, but you can extend them. Any class that extends the abstract class has to provide the implementation to the abstract methods. Hence these classes can be used as a skeleton to similar classes where some common functionality may be required. Such functionality can also be embedded into these classes. Unlike interfaces, abstract classes can have method code also. So they are very useful.

这也可能有帮助:https://softwareengineering.stackexchange.com/questions/96947/why-should-i-declare-a-class-as-an-abstract-class

关于Java 方法 : @Override vs abstract,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14132285/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com