本文介绍了为什么静态方法不涉及多态(后期绑定)我看到错误,静态方法不能被覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 请考虑以下代码:class A{ public static void m(Number n){ System.out.println("Number A"); };}class B extends A{ public static int m(Number n){ System.out.println("Number B"); return 1; };}输出:我知道静态方法不涉及多态,因此我推断我的代码不可能覆盖。这个编译器消息对我来说很奇怪。I know that static methods doen't involve in polymorphism hence I infer that overriding is impossible for my code. This compiler message is strange for me.据我所知,覆盖是多态的一部分。我准备scjp,我担心在熟悉的问题上会犯错误。As I understand that overriding is part of polymorphism. I prepare for scjp and I am afraid make mistake in familiar question.请澄清这个问题。我的预期行为 - 有关重载错误的消息expected behaviour for me - message about overloading error P.S1。我已阅读有关静态覆盖的热门问题,但我没有找到答案(I have read top popular question about static overridden and I didn't found answer( P.S2。 根据Pshemo回答:P.S2.According Pshemo answer:此代码:class Foo{ public static void m(Number n){ System.out.println("Number A"); }; public static int m(Number n){ System.out.println("Number B"); return 1; };} 输出:outputs:error: method m(Number) is already defined in class Foo public static int m(Number n){ ^1 error对我来说,这些情况是一样的。但编译器错误不同 - 很奇怪。For me these situations are same. But compiler error is different - strange.推荐答案JLS§8.4.8.3(Java 8)sa ys:JLS §8.4.8.3 (Java 8) says:同样的规则同时适用于实例方法和静态方法,因为它表示覆盖或隐藏。基本上,如果你有一个具有相同名称和相同参数的方法,它会覆盖它是一个实例方法,但如果它是一个类(静态)方法则隐藏(继承方法)。在这两种情况下,返回类型必须相同或遵守协方差规则。This same rule applies both to instance methods and static methods, since it says "overrides or hides". Basically, if you have a method with the same name and same parameters, it overrides if it's an instance method, but hides (the inherited method) if it's a class (static) method. And in both cases, the return type must either be the same or obey the rules for covariance.因为它是相同的规则,所以编译器中很可能只有一个地方检查此规则的代码,如果规则被违反,您将收到您正在看到的错误,我确信这是更常见的错误。编译器确实应该检查它是否应该说覆盖或隐藏,但看起来它们会滑落。完全正确地获取错误消息通常不是编译器编写者的最高优先级 - 与确保编译应该编译的代码并运行正确,而不应该编译的代码不相比。所以我认为这是一个缺陷,但非常小。Since it's the same rule, most likely there's just one place in the compiler code that checks this rule, and if the rule is violated you're getting the error you're seeing, which I'm sure is a much more common occurrence. The compiler really should check to see whether it should say "overrides" or "hides", but it looks like they slipped. Getting error message exactly right is not usually the highest priority of compiler writers--not compared to making sure code that's supposed to compile does so and runs right, and code that isn't supposed to compile doesn't. So I think this is a deficiency, but a very minor one. 这篇关于为什么静态方法不涉及多态(后期绑定)我看到错误,静态方法不能被覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-22 14:27