Search code examples
javainterfacedowncast

Why can we cast a Java interface to *any* non-final class?


import java.util.Collection;


public class Test
{
    public static void main(String[] args)
    {
        Collection c = null;
        Test s = null;

        s = (Test) c;
    }
}

In the code sample above, I am casting a collection object to a Test object. (ignoring the null pointer). Test has no relationship to Collection whatsoever, yet this program will pass all compile-time checks.

I'm wondering why this is. My assumption is that interfaces are ignored because they are too complicated. They have no common super-type and each class can implement several interfaces, so the class/interface hierarchy would be too complicated to search efficiently?

Other than that reason I am stumped though. Does anyone know?!


Solution

  • "Non-final" is a keyword here. You may have another class

    public class Test2 extends Test implements Collection
    

    whose instance will end up being assigned to s making a cast perfectly legal.