Java重写和重载在编译时抛出错误?

发布于 2024-11-06 20:50:16 字数 211 浏览 3 评论 0原文

我一直在编写一些关于方法重载和方法覆盖的示例。 方法重载是静态多态,重写是动态多态。

因此,与重载相关的任何错误都将在编译时被捕获。正确吗?或者是否存在由于不正确的重载而引发运行时异常的情况 - 我怀疑与

方法重写相关的任何错误( - 以防子类方法与基类具有相同的名称,并且与基类的参数相同----)将在编译时抛出。

上述两种情况是否存在运行时出现异常的情况?

I have been coding few examples on method overloading and method overridng.
Method overloading is static polymorphism and overriding is dynamic polymorphism.

So any error related to overloading will be caught at the compile time..Correct ?or are there any scenarios when a runtime exception is thrown because of incorrect overloading -- I Doubt

Any errors related to method overriding( -- incase when the child class method has same name as Base class and same arguments as of base class ---- )will be thrown at compile time .

Are there any scenarios in both the above cases where there is a exception at run time ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

悲歌长辞 2024-11-13 20:50:16

因此任何与重载相关的错误
会在编译时被捕获
时间..正确吗?或者有没有
运行时异常时的场景
由于不正确而抛出
超载——我怀疑

不,如果方法中的代码不抛出任何运行时异常,则不应该重载。

与方法相关的任何错误
覆盖(--以防孩子
类方法与 Base 具有相同的名称
类和与基类相同的参数
类 ---- ) 将在编译时抛出
时间。

这就是所谓的压倒一切。如果它不存在,那么如果您使用@Override,它可能会抛出编译时错误

So any error related to overloading
will be caught at the compile
time..Correct ?or are there any
scenarios when a runtime exception is
thrown because of incorrect
overloading -- I Doubt

No it shouldn't if your code from the method doesn't throw any runtime exception.

Any errors related to method
overriding( -- incase when the child
class method has same name as Base
class and same arguments as of base
class ---- )will be thrown at compile
time .

This is what is called overriding. if its not there then it may throw compile time error if you use @Override

百善笑为先 2024-11-13 20:50:16

我无法想象方法重载如何导致运行时异常。

不正确/不完整的方法重写的一些场景可能会导致运行时异常:

  1. 基方法是抽象的,而子类没有实现它 - 当父类重新编译添加新方法,而子类没有重新编译时,可能会发生这种情况(有缺陷的惰性编译,或者位于不同 jar 中的类等)
  2. 从基类的构造函数中调用重写方法
  3. 相关1:基方法不是抽象的,但签名改变了,而子类没有重新编译。所以它不会导致编译错误并且会在运行时飞行。

I cannot imagine how method overloading can cause a runtime exception.

Some scenarios when incorrect/incomplete method overriding can cause runtime exceptions:

  1. Base method is abstract, while it was not implemented by the child class - this may happen, when the parent class was recompiled adding new method, while the child class was not recompiled (buggy lazy compilation, or classes located in different jars, etc)
  2. Overriden method is called from the constructor of a base class.
  3. Related to 1: the base method is not abstract, but the signature was changed, while the child class was not recompiled. So it didn't caused the compilation error and will fly in runtime.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文