4

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.

code-gijoe
  • 6,949
  • 14
  • 67
  • 103
  • 5
    Before you go full-throttle into using `instanceof`, have a look at posts like this, as using `instanceof` is often a sign of a design flaw: http://stackoverflow.com/questions/2750714/is-instanceof-considered-bad-practice-if-so-under-what-circumstances-is-instanc and http://stackoverflow.com/questions/2790144/avoiding-instanceof-in-java – Abel Jul 24 '10 at 13:36
  • Consider using and interface, that way you'll get rid of all the nuances and restrictions imposed to you by the single inheritance model of java. public interface IFoo{ public void foo();} – Jose Diaz Jul 24 '10 at 14:28

4 Answers4

7

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
  • 42,159
  • 20
  • 102
  • 127
  • Thanks, I will consider changing my design. It's just that it adds a lot of boilerplate to always use type C. – code-gijoe Jul 24 '10 at 14:11
  • instanceof is like goto, if you use it then you need to take time and refactor your source :) – vach Dec 24 '14 at 14:18
3

You can check the type before casting using instanceof

Object obj = getAB_Or_C();

if ( obj instanceof C ) {
  C c = (C) obj;
}
stacker
  • 68,052
  • 28
  • 140
  • 210
2

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
  • 525,659
  • 79
  • 751
  • 1,130
2

As an alternative to instanceof, consider

interface Fooable { void foo(); }

class A implements Fooable { ... }
trashgod
  • 203,806
  • 29
  • 246
  • 1,045