DsCpp
DsCpp

Reputation: 2489

Java casting between two presumably unrelated classes

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?

Upvotes: 3

Views: 178

Answers (1)

Eran
Eran

Reputation: 393841

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.

Upvotes: 6

Related Questions