Alex Rivera | Logout

Java rules for casting

Asked 2010-02-10T01:53:31.217
25

When can a certain object be cast into another object? Does the casted object have to be a subtype of the other object? I'm trying to figure out the rules...

Edit: I realized that I didn't explain my issue at all: basically I am casting an object to an interface type. However, at run-time, I get a java.lang.ClassCastException. What needs to happen with my object so that I can cast it to this interface? Does it have to implement it?

Thanks

Edit
Report

1 Answer

4

This will work:

class Foo implements Runnable {
    public void run() {}
}

Foo foo = new Foo();
System.out.println((Runnable) foo);

But this will not:

class Bar {
    public void run() {}
}

Bar bar = new Bar();
System.out.println((Runnable) bar);

Because although Bar has a run() method that could implement Runnable.run(), Bar is not declared to implement Runnable so it cannot be cast to Runnable.

Java requires that you declare implemented interfaces by name. It does not have duck typing, unlike some other languages such as Python and Go

answered 2010-02-10T11:36:23.417

Your Answer