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.

2
  • 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: stackoverflow.com/questions/2750714/… and stackoverflow.com/questions/2790144/avoiding-instanceof-in-java Commented Jul 24, 2010 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();} Commented Jul 24, 2010 at 14:28

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I will consider changing my design. It's just that it adds a lot of boilerplate to always use type C.
instanceof is like goto, if you use it then you need to take time and refactor your source :)
3

You can check the type before casting using instanceof

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

Comments

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

2 Comments

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.
I can't change class A - it's part of GWT UI package.
2

As an alternative to instanceof, consider

interface Fooable { void foo(); } class A implements Fooable { ... } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.