Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java casting between two presumably unrelated classes

Tags:

java

casting

I'm trying to understand how the java compiler works regarding type casting but I can't figure it out.

please see the following code

    public class SampleTester{
    public static interface A1{}
    public static class A2{}
    public static class A3 extends A2 implements A1{
        public static void main(String[] args){
            List<A1> test = new ArrayList<>();
            test.add(new A3());
            A2 a2 = (A2) test.get(0);
        }
    }
}

this code compiles, but if I change

A2 a2 = (A2) test.get(0);

to

A2 a2 = (Integer) test.get(0);

It gives a compilation error.

Type mismatch: cannot convert from Integer to SampleTester.A2

as I see it, A2 is not related to A1 in any way (exactly as the integer isn't related), so how come the cast work?

like image 725
DsCpp Avatar asked Mar 08 '26 22:03

DsCpp


1 Answers

First of all, the title of your question is incorrect - you are not casting between two classes - you are casting an expression whose type is an interface type to a class type.

test.get(0) is of type A1, an interface. Even though A2 doesn't implement that interface, some sub-class of A2 may implement the interface (and actually you defined such a class - A3), so the cast can succeed. Therefore the compiler allows it.

Integer cannot be sub-classed (it's a final class), so there won't ever be a sub-class of Integer that implements A1. Since the cast can never succeed, the compiler doesn't allow it.

like image 188
Eran Avatar answered Mar 11 '26 11:03

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!