gpt4 book ai didi

java - 类型不明确的方法 - 为什么不解析

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:47:07 25 4
gpt4 key购买 nike

public class Animal {}

public class Bird extends Animal {}

public class Mamal extends Animal {}

public class Human extends Mamal {}

public class Main {

public void Hungry(Mamal mamal){
System.out.println("Mammal");
}
public void Hungry(Human human){
System.out.println("Human");
}
public void Hungry(Bird bird){
System.out.println("Bird");
}
public static void main(String a[]){
Main main = new Main();
main.Hungry(null);
}

编译器说 Hungry(Mamal) 方法不明确。我希望执行“人类”方法,因为它是最低级别。我没能从http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12中找到歧义的原因

最佳答案

HumanBird在继承层次结构中处于同一级别(虽然不是视觉上的)。或者将它们视为完全不相关的引用类型。因此,一个并不比另一个更具体。

如果删除 Hungry(Bird)方法,您的代码将编译。

更具体的规则是here .

One fixed-arity member method named m is more specific than another member method of the same name and arity if all of the following conditions hold:

  • The declared types of the parameters of the first member method are T1, ..., Tn.

  • The declared types of the parameters of the other method are U1, ..., Un.

  • If the second method is generic, then let R1 ... Rp (p ≥ 1) be its type parameters, let Bl be the declared bound of Rl (1 ≤ l ≤ p), let A1 ... Ap be the type arguments inferred (§15.12.2.7) for this invocation under the initial constraints Ti << Ui (1 ≤ i ≤ n), and let Si = Ui[R1=A1,...,Rp=Ap] (1 ≤ i ≤ n).

  • Otherwise, let Si = Ui (1 ≤ i ≤ n).

  • For all j from 1 to n, Tj <: Sj.

  • If the second method is a generic method as described above, then Al <: Bl[R1=A1,...,Rp=Ap] (1 ≤ l ≤ p).

所以你有

public void Hungry(Human human){
System.out.println("Human");
}
public void Hungry(Bird bird){
System.out.println("Bird");
}

所以 HumanT1BirdU1 (也尝试相反)。方法不是通用的。

S1 = U1

对于所有 j从 i 到 n(1 到 1),这应该是:Ti <: Si , 其中<:

We write T <: S to indicate that that the subtype relation holds between types T and S.

这不适用于我们的两种方法 Human不是 Bird 的子类型反之亦然,因此没有更具体的调用方法,即。歧义。

就好像你有一样

void method(String s){}
void method(RandomReferenceType t) {}

并尝试调用

method(null);

关于java - 类型不明确的方法 - 为什么不解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22119962/

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