Java can not figure out the method to be invoked

Mikhailov Valentine :

I haven't found the reason (in JLS) why java compiler can't chouse appropriate method to execute in following program:

public class UpperLevelClass {
    private static String getStringanotherNameMethod(String a, String b) {
        return null;
    }

    private static String firstSignatureMethod(String a, String b) {
        return null;
    }

    static class StaticNestedClass extends UpperLevelClass{
        public void getStringfirstNameMethod(String a, Integer b) {
            getStringanotherNameMethod("test", "fff");//compiles
            firstNameMethod("test", "fff");//error below
        }
    }
}

Compiling finishes with following error:

error: method firstNameMethod in class StaticNestedClass cannot be applied to given types;
            firstNameMethod("test", "fff");
            ^
  required: String,Integer
  found: String,String
  reason: argument mismatch; String cannot be converted to Integer

Adding some history:

At first I had several static method with default access in upper level calls and everething compiles and runs(from static nested class) fine. Then static methods access was changed to private and programm stops compiling due to error in one method (in this case firstNameMethod), but other methods compiles fine.


I have tried(thx to @Jorn Vernee) to compile and run programm in Eclipse and it compiles and runs.

Joe C :

Searching for the appropriate method is a two-step process.

Step 1 involves selecting the class to be searched. The relevant line of the JLS of this step:

If the Identifier appears in the scope of a visible method declaration with that name:

If there is an enclosing type declaration of which that method is a member, let T be the innermost such type declaration. The class or interface to search is T.

Note that it says Identifier and not Signature here. This means that it is only looking at the method name at this stage, and not the arguments. Because StaticNestedClass contains a method called getString, that is the class to be searched.

It is only when we get to Step 2 that arguments are taken into account. Because there is no getString method in StaticNestedClass that are compatible with the method call, this leads compilation to fail.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=86825&siteId=1