java - Method Overloading for null argument -


i have added 3 methods parameters:

public static  void dosomething(object obj) {     system.out.println("object called"); }  public static  void dosomething(char[] obj) {     system.out.println("array called"); }  public static  void dosomething(integer obj) {     system.out.println("integer called"); } 

when calling dosomething(null) , compiler throws error ambiguous methods. issue because integer , char[] methods or integer , object methods?

java try use specific applicable version of method that's available (see jls §15.12.2).

object, char[] , integer can take null valid value. therefore 3 version applicable, java have find specific one.

since object super-type of char[], array version more specific object-version. if 2 methods exist, char[] version chosen.

when both char[] , integer versions available, both of them more specific object none more specific other, java can't decide 1 call. in case you'll have explicitly mention 1 want call casting argument appropriate type.

note in practice problem occurs far more seldom 1 might think. reason happens when you're explicitly calling method null or variable of rather un-specific type (such object).

on contrary, following invocation unambiguous:

char[] x = null; dosomething(x); 

although you're still passing value null, java knows method call, since take type of variable account.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -