Java:覆盖还是重载方法? [英] Java: Overriding or Overloading method?

查看:27
本文介绍了Java:覆盖还是重载方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法,在一个名为PlaceParser"的类中,它扩展ModelParser":

I have a method, in a class called "PlaceParser" that extends "ModelParser":

protected Place parseModel(JSONObject element) ...

地点是模型的子类.上面的代码要不要加上@Override注解?由于该方法具有不同的返回类型,这是否仍算作覆盖具有相同名称和参数的基类方法/返回类型是否改变了签名"?

A Place is a sub class of Model. Should the @Override annotation be added to the above code? As the method has a different return type, does this still count as overriding the base class method with the same name and arguments / does the return type alter the 'signature'?

ModelParser"方法看起来像这个ModelT"也扩展了Model":

The "ModelParser" method looks like this "ModelT" also extends "Model":

protected abstract ModelT parseModel(JSONObject element)
            throws JSONException;

<小时>

更新@Jon Skeet:

基类声明如下:

public abstract class ModelParser<ModelT extends Model> {

我以前从未见过类的 样式声明.

I hadn't seen a <ModelT extends Model> style declaration for a class before.

推荐答案

是的,您应该添加 @Override,因为您仍在覆盖该方法.您使用返回类型协方差的事实不会改变这一点.

Yes, you should add @Override, as you're still overriding the method. The fact that you're using covariance of return types doesn't change that.

特别是,如果其他代码具有 ModelParser 类型的表达式并调用 parseModel(element),它们仍然会在你的中以多态结束执行.将其与 重载(例如通过添加另一个参数)进行比较,其中将调用 ModelParser 中的原始实现.

In particular, if other code has an expression of type ModelParser and calls parseModel(element) they will still end up polymorphically in your implementation. Compare that with overloading (e.g. by adding another parameter) where the original implementation in ModelParser would be called.

这篇关于Java:覆盖还是重载方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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