gpt4 book ai didi

Java:编译时解析和 "most specific method"

转载 作者:搜寻专家 更新时间:2023-11-01 00:58:21 25 4
gpt4 key购买 nike

重载函数 compute1()compute2()compute5() 如果您尝试在下面使用它们,则会导致编译错误:

package com.example.test.reflect;

class JLS15Test2
{
int compute1(Object o1, Integer i, Integer j) { return 1; }
int compute1(String s1, Integer i, int j) { return 2; }

int compute2(Object o1, Integer i, int j) { return 3; }
int compute2(String s1, Integer i, Integer j) { return 4; }

int compute3(Object o1, Integer i, int j) { return 5; }
int compute3(String s1, Integer i, int j) { return 6; }

int compute4(Object o1, Integer i, Integer j) { return 7; }
int compute4(String s1, Integer i, Integer j) { return 8; }

int compute5(Object o1, Integer i, Object j) { return 9; }
int compute5(String s1, Integer i, int j) { return 10; }


public static void main(String[] args)
{
JLS15Test2 y = new JLS15Test2();

// won't compile:
// The method compute1(Object, Integer, Integer) is ambiguous
// for the type JLS15Test2
// System.out.println(y.compute1("hi", 1, 1));

// Neither will this (same reason)
// System.out.println(y.compute2("hi", 1, 1));
System.out.println(y.compute3("hi", 1, 1));
System.out.println(y.compute4("hi", 1, 1));

// neither will this (same reason)
// System.out.println(y.compute5("hi", 1, 1));
}
}

阅读 JLS 15.12 节后,我想我明白了......在匹配重载方法的第 2 阶段(允许装箱/拆箱,无可变参数),在确定“最具体的方法”时,JLS 说(实际上)最具体的方法是其形式参数是其他适用方法的子类型的方法,而基元和对象(例如 intInteger)永远不是彼此的子类型。所以IntegerInteger的子类型,intint的子类型,但是Integerint 不兼容 w/r/t 子类型比较,因此 compute1()/compute2() 对都没有最具体的方法。

(而在 compute3()compute4() 中,带有 String 参数的方法比带有 Object 参数,因此程序打印 6 和 8。)

我的推理是否正确?

最佳答案

是的,你的推理是正确的。

关于Java:编译时解析和 "most specific method",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6062027/

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