Java 方法:@Override 与抽象 [英] Java methods: @Override vs abstract

查看:57
本文介绍了Java 方法:@Override 与抽象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下其中一种样式来声明抽象父类中的方法的优点/缺点是什么:

What are the advantages/disadvantages of using one of the following styles over the other for declaring a method from an abstract parent class:

选项 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 与抽象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆