简体   繁体   中英

Method overloading with floating types

What will be the output of following code?The output is coming to be 1.0 but this means it is giving preference to double parameters instead of floating parameter. Please someone explain what is the mechanism behind this output.

class X
    {

     int method(int i)
    {

        return i *= i;
    }
}

class Y extends X
{
    double method(double d)
    {
        return d /= d;    
    }
}
class Z extends Y
{
    float method(float f)
    {
        return f += f;
    }
}

public class MainClass
{
    public static void main(String[] args)
    {
        Z z = new Z();

        System.out.println(z.method(21.12));
    }
 }

21.12 is a double literal, which is why double method(double d) is chosen. For float literals you have to use 21.12f or 21.12F . z.method(21.12f) would invoke float method(float f) .

Because by default the decimal number type is double in java so at this point

 System.out.println(z.method(21.12));

java gonna consider 21.12 values is a double not float hence java look-up table try to find the best match with double value

The float literals as marked with either f or F so to call function with floating values do this

 System.out.println(z.method(21.12f));

Your literal 21.12 is treated as a double by the runtime. You could try "21.12F" to explicitly make it into a float.

By default, a floating point literal like 21.12 is interpreted as double by the compiler (you would need to use 21.12f to make it a float ).

So, at compile time, the compiler searches for that method that matches the most closest; in that case, the double-taking one from your base class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM