code-gijoe
code-gijoe

Reputation: 7244

How can I do a safe downcast and prevent a ClassCastException

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 class A, B or C and I want to cast safely to C but only if the class type is C. This is because I need to call Foo() but I don't want the ClassCastException.

Upvotes: 4

Views: 8925

Answers (4)

Simon Nickerson
Simon Nickerson

Reputation: 43157

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.

Upvotes: 7

trashgod
trashgod

Reputation: 205825

As an alternative to instanceof, consider

interface Fooable { void foo(); }

class A implements Fooable { ... }

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533620

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

Upvotes: 2

stacker
stacker

Reputation: 68972

You can check the type before casting using instanceof

Object obj = getAB_Or_C();

if ( obj instanceof C ) {
  C c = (C) obj;
}

Upvotes: 3

Related Questions