Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 1000
Shamal Sandeep Avatar asked May 21 '15 08:05

Shamal Sandeep


2 Answers

You are mixing up memory space of variables and their type. Calling the method m(...) will first of all check the type of the paramether variable. Here it is an int so it will chose the according overloaded method, no matter the size of the int in memory.

Although I really apreciate you first example that brings the light into one of the characteristics of the final identifier.

like image 64
Smallware Avatar answered Oct 22 '22 02:10

Smallware


This bit isn't quite correct...

"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."

It doesn;t store it as a byte, it stores it as an int, BUT it is effectively a constant so when Java compiles the line byte b = i; it knows for sure that the value will be 10, which doesn't need casting.

like image 37
Phil Anderson Avatar answered Oct 22 '22 02:10

Phil Anderson