Java - 重载方法采用接口作为参数。调用了哪个方法,为什么?
Java - Overloaded method takes interfaces for arguments. Which method is called and why?
我有一个实现两个接口(特别是 Serializable
和 java.security.Key
接口)的对象。这个对象的 class 也有两个静态方法:一个接受 Serializable
对象,一个接受 Key
对象。这是一些示例代码:
public class Subclass implements Serializable, java.security.Key{
public static void test(Serializable s) {
System.out.println("Ser");
}
public static void test(java.security.Key k) {
System.out.println("Key");
}
public static void main(String[]args){
test(new Subclass());
}
}
现在当我运行上面的主要方法时,没有抛出任何错误并且Java调用了test(Key)
方法。但是,当我将 Serializable
接口更改为其他内容时(我更改 test(Serializable)
中的参数并将 Subclass
的超级接口更改为其他内容时,我的 IDE 显示我有一个错误:
The method test(Key)
is ambiguous for the type SubClass
.
我想知道的是,为什么 Java 允许这种方法与 Serializable
接口而不是其他接口有歧义?
之所以起作用并调用 test(java.security.Key k)
是因为 java.security.Key
扩展了 Serializable
本身,因此 java.security.Key
更专业 比 Serializable
更适合方法调用。
我有一个实现两个接口(特别是 Serializable
和 java.security.Key
接口)的对象。这个对象的 class 也有两个静态方法:一个接受 Serializable
对象,一个接受 Key
对象。这是一些示例代码:
public class Subclass implements Serializable, java.security.Key{
public static void test(Serializable s) {
System.out.println("Ser");
}
public static void test(java.security.Key k) {
System.out.println("Key");
}
public static void main(String[]args){
test(new Subclass());
}
}
现在当我运行上面的主要方法时,没有抛出任何错误并且Java调用了test(Key)
方法。但是,当我将 Serializable
接口更改为其他内容时(我更改 test(Serializable)
中的参数并将 Subclass
的超级接口更改为其他内容时,我的 IDE 显示我有一个错误:
The method
test(Key)
is ambiguous for the typeSubClass
.
我想知道的是,为什么 Java 允许这种方法与 Serializable
接口而不是其他接口有歧义?
之所以起作用并调用 test(java.security.Key k)
是因为 java.security.Key
扩展了 Serializable
本身,因此 java.security.Key
更专业 比 Serializable
更适合方法调用。