gpt4 book ai didi

java - 静态和非静态相互重载

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:24:55 26 4
gpt4 key购买 nike

这两个函数是否重载

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 :

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),但它是完全有效的。

有趣的是,这可能会导致重载决策出现问题,因为即使没有实例可以调用该方法,实例方法也会被包含在内。例如:

public class Test {
public void foo(String x) {
}

public static void foo(Object x) {
}

public static void bar() {
foo(""); // Error
}
}

规范可以被设计成这样就可以了(并调用静态方法)但它是一个错误:

Test.java:9: error: non-static method foo(String) cannot be referenced
from a static context
foo("");
^

关于java - 静态和非静态相互重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29581500/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com