Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behavior with java overloading

i've some problems with java overloading and dynamic parameters..

import java.lang.*;

public class Program
{
     public static void main(String []args){
        testOverloading("Test string");
        testOverloading(new Object());
        testOverloading( true ? "Must be a string" : new Object());
     }

     public static void testOverloading(String test) {
         System.out.println("it's a string");
     }

     public static void testOverloading(Object test) {
         System.out.println("it's an object");
     }

}

running this code the java assume that "true ? "Must be a string" : new Object()" is an object and not a string..and the output is the follow:

it's a string
it's an object
it's an object

is there a solution/explaination for this kind of issue?

Update:

i tried also using a different approach:

changing:

testOverloading( true ? "Must be a string" : new Object());

in

testOverloading( true ? "Must be a string" : new Program());

and

public static void testOverloading(Object test) {

in

public static void testOverloading(Program test) {

and the output is:

error: no suitable method found for testPoly(Object)

so i've to assume that it's a compiler limitation with parameters that use single-line condition

in fact using normal the output is right:

    if (true)
        testOverloading("Must be a string");
    else
        testOverloading(new Object());

output: it's a string
like image 657
Joseph Avatar asked Feb 13 '26 19:02

Joseph


1 Answers

true ? "Must be a string" : new Object() should have a single type of return. In this case, the compiler will choose the highest class in the class hierarchy for the elements being returned, which is Object.

like image 147
Luiggi Mendoza Avatar answered Feb 15 '26 10:02

Luiggi Mendoza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!