我有以下简单的 Java 代码:
爪哇
import static a.A1.*;
import static a.A2.*;
class Main {
public static int g() {return 999;}
static {
System.out.println("f('a'): " + f('a'));
System.out.println("f(): " + f());
//System.out.println("g('a'): " + g('a'));
System.out.println("g(): " + g());
}
}
a/A1.java
package a;
public class A1 {
public static int f(char x) {return 1;}
public static int g(char x) {return 123;}
}
a/A2.java
package a;
public class A2 {
public static int f() {return 0;}
}
f
定义了两次,带有重载参数。如您所见,f
静态导入两个定义并调用它们是有效的:
$ javac *.java a/*.java && java Main
f('a'): 1
f(): 0
g(): 999
Exception in thread "main" java.lang.NoSuchMethodError: main
但是当我g
在本地定义以及从某个地方静态导入它时,它不起作用。这是我在 Main.java 中取消注释第 8 行时的输出:
$ javac *.java a/*.java && java Main
B.java:8: g() in Main cannot be applied to (char)
System.out.println("g('a'): " + g('a'));
^
1 error
为什么?
我尝试将本地g
更改为非静态,并删除对本地的调用g
:
import static a.A1.*;
import static a.A2.*;
class Main {
public int g() {return 999;}
static {
System.out.println("f('a'): " + f('a'));
System.out.println("f(): " + f());
System.out.println("g('a'): " + g('a'));
}
}
但它没有用:
$ javac *.java a/*.java && java Main
B.java:8: g() in Main cannot be applied to (char)
System.out.println("g('a'): " + g('a'));
^
1 error