Cast reference of known type to an interface outside of type's hierarchy

Say you have a clean class like this:

public class A {
    // Stuff
}

And a interface like this:

public interface G {
    // Stuff
}

Why am I allowed to do this:

A a = new A();
((G) a) // No errors thrown

I can't understand why it should be possible to cast from the class A to the interface G when they have nothing to do with each other. Can someone please explain this to me?


Follow-up. If I make the following:

public class C implements G {
    // Stuff
}

This won't compile:

((C) a)

What is the difference between a class that implements a interface and just the interface?

EDIT: I get a compiler-error saying:

Cannot cast from A to C

Answers


Casting means you know better than the compiler what's valid. You are telling the compiler to shut up and follow your lead. The compiler can tell in a few cases that a cast is invalid, but it is easy to fool.

Most casts tend to be from Object to something else, such as in getting an object out of a non-genericized collection or when getting a remote object using PortableRemoteObject.narrow. These casts always compile because whatever you cast to (as long as it's an Object, and not a primitive) is always a valid subclass of Object.

There are some rules for casting in the Java language specification in the section Reference Type casting (5.5.1). If the compiler can figure out there is no relationship between the classes (the compiler can tell the classes are different and neither is a subclass of the other) then it will reject the cast.

The added example is interesting, it fails because the compiler has enough information to tell that the cast is invalid. If you change the code to:

    A a = new A();
    G g = (G)a;
    Object o = a;
    C c = (C)o;

then it compiles fine again (even though it is just as erroneous).


Need Your Help

Handling big data sets (neo4j, mongo db, hadoop)

mongodb hadoop neo4j

I'm looking for best practices to handle data. So, that is what I got so far: 1.000.000 nodes of type "A". Every "A" node can be connected to 1-1000 nodes of type "B" and 1-10 nodes of type "C".

Reload/refresh jquery ui slider with checkbox checking

jquery user-interface checkbox slider

I have a little problem with jquery ui slider and checkboxes.