Java中关于int/long和String/object的参数的方法重载 [英] Method overloading in java regarding arguments with int/long and String/object

查看:263
本文介绍了Java中关于int/long和String/object的参数的方法重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下程序,为什么要调用具有int和String参数的方法而不是long和Object?

For the following program why the methods with int and String arguments are getting called instead of long and Object?

想知道为什么编译器选择long上的longObject参数上的int.

Wanted to know why the compiler is choosing int over long and String over Object arguments.

注意:这是在采访中问到的.

Note: This was asked in an interview.

public class MethodOverloadingTest {

    public static void add(int n, int m){
        System.out.println("Int method");
        System.out.println(n+m);
    }

    public static void add(long n, long m){
        System.out.println("Long method");
        System.out.println(n+m);
    }

    public static void method(String st){
        System.out.println("from String method");
    }

    public static void method(Object obj){
        System.out.println("from Object method");
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        add(2,3);
        method(null);
    }

}

推荐答案

对于add(2,3)方法,您正在传递整数,这就是为什么要调用整数的原因. 对于method(null),选择最具体的方法参数.在这种情况下,StringObject更具体.因此method(String st);被调用.

For the add(2,3) method, you are passing integers, that's why integers are getting called. For method(null), the most specific method argument is chosen. In this case, String is more specific than Object. Hence method(String st); gets called.

这篇关于Java中关于int/long和String/object的参数的方法重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆