Which method is looked first by Compiler , Static or instance method when ClassName.method() is used?

前端 未结 4 1286
忘了有多久
忘了有多久 2021-01-16 06:44

I want to get proper understanding why below compilation error? As per my understanding If i use Test.xyz() then compiler look for only static method not for instance method

4条回答
  •  孤街浪徒
    2021-01-16 07:23

    Ok, So here comes the concept of autoboxing in Java.

    U wrote:

    Test.xyz(10); // Here 10 is a primitive int and not a java.lang.Integer object.  
    

    But since you are invoking the xyz method directly via class name, clearly means you want to access the public static xyz(Integer) method of the class Test.

    But what happens in the compilation process is, first your javac compiler checks for method signature that is to be accessed, and after that, it checks for it's access(public, private, protected, default) and non-access(final, static, etc) modifiers.

    The same thing happened with this code.

    The first thing Java did was, it checked for the existence of the method with the signature xyz(int) and not xyz(Integer) coz you've passed in 10 and not new Integer(10) as a parameter.

    It found two methods,
    1. xyz(int)
    2. xyz(Integer)

    Had xyz(int) not existed, it would have applied the concept of autoboxing(ie, automatically convert 10 to new Integer(10)) and selected xyz(Integer) to be executed. But since xyz(int) exists, it does not autobox 10 to new Integer(10) and selects xyz(int) instead of xyz(Integer).

    Now since your compiler has selected xyz(int) to be executed, it checks for it's non-access modifiers. Now since the method xyz(int) is non-static, you are expected to access it with an object of Test class as follows:

    new Test().xyz(10);  
    

    And still, if you want to access the static xyz(Integer) method, you may have to use:

    Test.xyz(new Integer(10)); // You have to maunally autobox it.  
    

    Hope this helps.

提交回复
热议问题