java - char 到 int 的隐式转换(或缺少转换)
问题描述
我正在为我的 OCA 考试而学习,并从 Mala Gupta 那里遇到了这个问题:
class Course { void enroll(long duration) { System.out.println("long"); } void enroll(int duration) { System.out.println("int"); } void enroll(String s) { System.out.println("String"); } void enroll(Object o) { System.out.println("Object"); } }
以下代码的输出是什么?
class EJavaGuru { public static void main(String args[]) { Course course = new Course(); char c = 10; course.enroll(c); course.enroll("Object"); } } a. Compilation error b. Runtime exception c. int String d. long Object
正确答案是 (c),我在运行代码后也进行了验证。但是,为什么数据类型会在方法调用中char
扩大到一个?int
根据我对Java中数据类型隐式转换的了解,默认情况下achar
不会隐式转换为an int
。
TL;DR:为什么以下代码不起作用
int x = 5;
char c;
c = x; // Compliation error here
但这有效:
static void intParameterMethod( int someInt ) {}
public static void main( String args[] ) {
char c = 5;
intParameterMethod( c ); // No compilation error here
}
解决方案
推荐阅读
- c - 直接在汇编中使用 stdlib.h 函数
- multithreading - 在统一调用繁重的函数时避免游戏冻结的最简单方法是什么?
- r - R在Windows10上启动-“系统找不到指定的路径。” 信息。我怎样才能找到路径?
- java - 改进的带线程的递归冒泡排序
- linux - 如何在 AWS EC2 上找到 100% CPU 利用率的原因?
- swift - Xcode 11 分段错误:存档期间为 11
- powerbi - Custom Realtime Data in PowerBI Dashboards
- database - 并发写入共享网络资源
- python - Running MS Access through Python
- c# - GameObject' does not contain a definition for 'AddForce' || Unity3D