Skip to content
Advertisement

how do i settle this overloading java

how to calculate 2 number integer and float by using overloading in java

class Darab{
    float HasilDarab(int a ,int b){
        int total;
        total= a*b;
        return total;
    }
    float HasilDarab(float a ,float b){
        float total;
        total=a*b;
        return total;
    }
}

class MethodOverloading {
    public static void main(String[] args) {
        float hasildarab1,hasildarab2,a=5,b=6;

        Darab obj1=new Darab();
        hasildarab1=obj1.HasilDarab(a,b);
        hasildarab2=obj1.HasilDarab(a,b);

        System.out.println("Hasil darab dalam interger"+hasildarab1);
        System.out.println("Hasil darab dalam float"+hasildarab2);

    }
}

this is my code but i still get both of them is float

Advertisement

Answer

You define your a and b variables as float, so Java selects the method that has parameters of type float, because, in addition to a method name, Java uses parameter types to differentiate between methods. See more here.

Try to rewrite your code as:

float hasildarab1, a = 5, b = 6;
int hasildarab2, c = 5, d = 6;

Darab obj1 = new Darab();
hasildarab1 = obj1.HasilDarab(a, b);
hasildarab2 = obj1.HasilDarab(c, d);

UPD: Also, as Dawood ibn Kareem correctly mentioned in the comment, you need to change the return type of the first HasilDarab method to int.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement