Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?!

like image 555
ares Avatar asked Dec 22 '22 10:12

ares


1 Answers

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

like image 53
ChssPly76 Avatar answered Dec 30 '22 02:12

ChssPly76