相互之间是静态和非静态的重载 [英] are static and non static overloads each other
问题描述
这两个函数是否重载
class yogi{
public static void fun(){
System.out.println("Fun");
}
public void fun(int a,int b){
System.out.println("int");
}
}
推荐答案
是的,那些是超载。来自 JLS 8.4.9 :
Yes, those are overloads. From JLS 8.4.9:
如果一个类的两个方法(无论是在同一个类中声明,还是由一个类继承,或者声明一个和一个继承的)具有相同的名称,但签名不是覆盖等价的,然后方法名称被称为重载。
If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded.
对于静态和实例方法具有相同名称而言,它是一个相当罕见的(IMO),但它完全有效。
It's fairly rare (IMO) for it to be a good idea to have the same name for both static and instance methods, but it's entirely valid.
有趣的是,这可能会导致重载解析中的问题,即使没有实例调用方法,实例中也会包含方法。例如:
Interestingly, this can cause problems in overload resolution, in that instance methods are included even when there's no instance to call the method on. For example:
public class Test {
public void foo(String x) {
}
public static void foo(Object x) {
}
public static void bar() {
foo(""); // Error
}
}
规范可以已被设计为可以正常(并调用静态方法),但它是一个错误:
The spec could have been designed so that this would be fine (and call the static method) but instead it's an error:
Test.java:9: error: non-static method foo(String) cannot be referenced
from a static context
foo("");
^
这篇关于相互之间是静态和非静态的重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!