final casting concept doesn’t apply for overloading

In my casting class, teacher taught us an interesting fact as follows.

class Casting {
    public static void main(String args[]){
        int i = 10;
        byte b = i;
        System.out.println(b);
    }
}

We got an error

java:5: possible loss of precision

And then we changed the code as follows

class Casting1 {
    public static void main(String args[]){
        final int i = 10;
        byte b = i;
        System.out.println(10);
    }
}

10

We got the correct output. As for the reason, he told that when we modify a variable final the variable is stored in the smallest data type possible. In this case was a byte. That’s the reason that we were able to cast that without using the cast keyword.

But when we use method overloading like this,

class A {
    void m(int i){
        System.out.println("int");
    }
    void m(byte b){
        System.out.println("byte");
    }
    public static void main(String args[]){
        A a1 = new A();
        final int i = 10;
        a1.m(i);
    }
}

I get the output int. If the final variables are stored in the lowest possible data type, it should be byte. So I tried the following code without overloading.

class A {
    void m(byte b){
        System.out.println("byte");
    }
    public static void main(String args[]){
        A a1 = new A();
        final int i = 10;
        a1.m(i);
    }
}

java:9: m(byte) in A cannot be applied to (int)

What’s the reason for this? Is there any point that I have misunderstood?


Source: java

Leave a Reply