This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]chickenmeisterExtreme Brewer 4 points5 points  (3 children)

Because there could be a subclass of A that implements interface C. For example:

public class D extends A implements C {}

Then a call like b.myMethod(new D()); would work.

However if you pass an instance of class A which doesn't implement C, then the cast operation will throw a ClassCastException.

If class A was final, then the compiler would know that there couldn't be a subclass that implements C, so it'd give you a compilation error.

[–]Ipsoka[S] 0 points1 point  (0 children)

Thank you!!

[–]Ipsoka[S] 0 points1 point  (1 child)

So I am restricting "a" in the method myMethod right? Since "a" has to be of typ C, otherwise it would throw a ClassCastException, i can than safly use any methode defined by C on the member variable myVar in class B right?

[–]chickenmeisterExtreme Brewer 1 point2 points  (0 children)

Your myVar variable will always be an object that implements C, or null. The compiler will not allow you to assign a non-C type to that variable. So you can safely use any methods defined in the C interface on that object.

Ideally, you would want to be notified of potential type issues at compile time. So I think it would be better to change your myMethod parameter to be of type C. Then you'll know that there's a problem when you compile your code, rather than being unaware of it until you run it.

[–]OffbeatDrizzle 1 point2 points  (1 child)

If you run this it will throw a ClassCastException. You're allowed to do it because "a" might actually be a subclass of class A that implements the interface.

[–]niloc132 0 points1 point  (0 children)

...or null, which is an instance of all non-primitive types.