JAVA Object / String方法重载

编程入门 行业动态 更新时间:2024-10-28 03:29:07
本文介绍了JAVA Object / String方法重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

出于好奇我试过这个例子。

Just out of curiosity I tried this example.

public class Class1 { public void method(Object obj){ System.out.println("Object"); } public void method(String str){ System.out.println("String"); } public static void main(String... arg){ new Class1().method(null); } }

输出为字符串。我想知道JVM决定以什么为基础调用String作为参数而不是Object的方法。

The output being "String". I want to know on what basis the JVM decides to invoke method taking String as argument and not Object.

推荐答案

每当不止一个重载方法可以应用于参数列表,使用最具体的方法。

Whenever more than one overloaded methods can be applied to the argument list, the most specific method is used.

在这种情况下,传递 null 时可以调用其中一个方法,因为null type是可分配的到对象和字符串。 String 的方法更具体,因此将被选中。

In this case either of the methods can be called when passing null, since the "null type" is assignable to both Object and to String. The method that takes String is more specific so it will be picked.

更多推荐

JAVA Object / String方法重载

本文发布于:2023-06-11 23:28:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/645231.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   JAVA   Object   String

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!