在子类中重新定义静态方法
我想知道为什么 Java 中首先允许这样做(或者一般来说哎呀) 我记得静态方法对于父类和子类都是通用的
public class Redefine extends Parent{
public static void test () {
}
}
class Parent{
public static void test () {
}
}
问题1:由于静态方法不支持重写,两个类如何包含相同的方法?
Q2:如果更改静态方法以引发未定义的异常,则无法编译。 为什么会这样。它显然不是压倒性的,所以我应该被允许抛出新的异常,对吗?
public class Redefine extends Parent{
public static void test () throws Exception{
}
}
I would like to know the reason why this is first allowed in Java (or oops in general)
I remember that the static methods are common for both parent and child class
public class Redefine extends Parent{
public static void test () {
}
}
class Parent{
public static void test () {
}
}
Q1 : Since Overriding is not supported for static methods , how can both classe contain same methods ?
Q2 : If change the method in static to throw an exception not defined its not compiling.
why is the case. Its obviously not overriding so i should be allowed to throw new exceptions right ?
public class Redefine extends Parent{
public static void test () throws Exception{
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
A1::
静态
方法是每个类的。就多态性而言,它们与继承层次结构无关。因此,调用Parent.test()
将调用父方法,而调用Redefine.test()
将调用子方法。A2: JLS 8.4 .8 写道:
A1::
static
method are per-class. They have nothing to do with inheritance hierarchies in terms of polymorphism. So callingParent.test()
will call the parent method, while callingRedefine.test()
will call the child.A2: JLS 8.4.8 writes:
你没有覆盖它,你隐藏它
http://faq.javaranch。 com/java/OverridingVsHiding
你得到了什么异常?
you arent overriding it, you are hiding it
http://faq.javaranch.com/java/OverridingVsHiding
what exception are you getting?
Q1:静态方法不会被重写,因此这是两个具有相同签名的不同方法。一个是用 Parent.test() 调用的,另一个是用 Redefine.test() 调用的。
Q2:你的方法似乎是有效的。你得到什么错误?
Q1: Static methods are not overridden, so these are two different methods with the same signature. One is called with Parent.test(), the other is called with Redefine.test()
Q2: Your method seems valid. What error do you get?