gpt4 book ai didi

java - 三元运算符如何评估结果数据类型?

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

给定这段代码

public class Main {

public static void main(String[] args) {
foo(1);
foo("1");
foo(true?1:"1");
foo(false?1:"1");
}

static void foo(int i){System.out.println("int");}
static void foo(String s){System.out.println("String");}
static void foo(Object o){System.out.println("Object");}
}

这是我得到的输出:

intStringObjectObject

I can't understand why in the last two cases foo(Object o) is invoked, instead of foo(int i) and foo(String s).Isn't the return type for a ternary expression evaluated at runtime?

Edit:

What was confusing me is the assertion that

System.out.println((y>5) ? 21 : "Zebra");

编译因为(OCA 学习指南 - Sybex):

The System.out.println() does not care that the statements are completely differnt types, because it can convert both to String

重点是 println 被重载以接受 Object 类型作为输入。相当具有误导性,恕我直言。

最佳答案

三元组的两个替代项必须属于同一类型。 Integer 和 String 的唯一通用类型是 Object,因此操作数都被强制转换为 Object,并且三元类型在编译时确定为 Object。

然后编译器静态绑定(bind)到带有 Object 参数的方法。

逻辑上三元结果在编译时可确定并不重要——编译器不会那样工作。它处理表达式和类型。它必须首先解析三元表达式的类型,而不是它的,为此它必须首先为操作数找到一个通用类型。

关于java - 三元运算符如何评估结果数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30534263/

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