不允许Java方法覆盖的超类型的原因是什么? [英] What is the reasoning behind not allowing supertypes on Java method overrides?

查看:134
本文介绍了不允许Java方法覆盖的超类型的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译器认为以下代码无效:



The following code is considered invalid by the compiler:

class Foo {
    void foo(String foo) { ... }
}

class Bar extends Foo {
    @Override
    void foo(Object foo) { ... }
}





我认为这是在JLS 8.4.8.1 :m1的签名是m2签名的子签名(§8.4.2)。而在8.4.2:相应类型变量的界限是相同的。



我的问题是:为什么不能在子类型中的参数(Bar)是超类型(Foo)中参数的超类型。在示例中,Object是String的超类型。据我所知,这不会违反 Liskov替代原则



是否存在允许这样会破坏代码的情况,或者它是当前JLS的限制?



I think that this is described in the JLS 8.4.8.1: "The signature of m1 is a subsignature (§8.4.2) of the signature of m2." and in 8.4.2: "the bounds of corresponding type variables are the same".

My question is: why can't the parameter in the subtype (Bar) be a supertype of the parameter in the supertype (Foo). In the example Object is a supertype of String. As far as I can see allowing this wouldn't violate the Liskov Substitution Principle.

Is there a scenario in which allowing this would break the code or is it a limitation of the current JLS?

推荐答案

答案很简单简单地说,在Java中,对于方法重写,您必须具有超类型的确切签名。但是,如果删除@Override注释,您的方法将会重载并且您的代码不会中断。这是一个Java实现,可以确保您的方法实现应该覆盖超类型的实现。



方法覆盖以下列方式工作。

The answer is plain simple, in Java, for method overriding, you must have the exact signature of the super type. However, if you remove the @Override annotation, your method would be overloaded and your code won't break. This is a Java implementation that ensures that you mean the method implementation should override the implementation of the super type.

Method overriding works in the following way.
class Foo{ //Super Class

  void foo(String string){

    // Your implementation here
  }
}

class Bar extends Foo{

  @Override
  void foo(String string){
    super(); //This method is implied when not explicitly stated in the method but the @Override annotation is present.
    // Your implementation here
  }

  // An overloaded method
  void foo(Object object){
    // Your implementation here
  }
}





上面显示的方法都是正确的,它们的实现可能会有所不同。

我希望这会对你有帮助。



The methods shown above are both correct and their implementation can vary.
I hope this helps you.


这篇关于不允许Java方法覆盖的超类型的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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