Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

overloading - Java overload confusion

java is not able to call any overload method as shown below :-

class LspTest{

    public void add(int a, float b){
    System.out.println("First add");
}

public void add(float a, int b){
    System.out.println("second add");
}

public static void main(String [] a){
    LspTest test = new LspTest();
    test.add(1,1);
   }
}

Please explain i am confused in this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In your methods you are having parameters (int, float) and (float, int) but when calling the method you are passing both the int (1,1) values. The Java complier can auto type cast float to int whenever needed. But in this case compiler cannot decide auto type cast which int to float. Therefore it shows ambiguity.

You need to call it test.add(1f, 1); or test.add(1,1f); i.e. specify which value is int and which value is float.

P.S. To specify a value to be float you can write f with it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...