views:

84

answers:

4

Hi, I have the following scenario:

public class A {
}

public class B extends A {
}

public class C extends B {
    public void Foo();
}

I have a method that can return me class A, B or C and I want to cast safely to C but only if the class I get is of type C. I need to call Foo() but I don't want the ClassCastException.

+4  A: 

Can you do this?

if (obj instanceof C) {
   ((C)obj).Foo();
}
else {
   // Recover somehow...
}

However, please see some of the other comments in this question, as over-use of instanceof is sometimes (not always) a sign that you need to rethink your design.

Simon Nickerson
Thanks, I will consider changing my design. It's just that it adds a lot of boilerplate to always use type C.
code-gijoe
+2  A: 

You can check the type before casting using instanceof

Object obj = getAB_Or_C();

if ( obj instanceof C ) {
  C c = (C) obj;
}
stacker
+2  A: 

What you should do is something like the following, then you don't need to cast.

public class A { 
    public void foo() {
        // default behaviour.
    }
} 

public class B extends A { 
} 

public class C extends B { 
    public void foo() {
       // implementation for C.
    }
} 
Peter Lawrey
SOmetimes, sometimes not. It doesn't always make sense for A to have a method foo(), and you might not be able to change the class A.
Simon Nickerson
I can't change class A - it's part of GWT UI package.
code-gijoe
Next time add such information to your question.
Thorbjørn Ravn Andersen
+1  A: 

As an alternative to instanceof, consider

interface Fooable { void foo(); }

class A implements Fooable { ... }
trashgod