views:

45

answers:

2

I have several classes that extend C and I would need a method that accepts any argument of type C. But in this method I would like to know if I'm dealing with A or B.

*

public A extends C
public B extends C

public void goForIt(C c)()

If I cast how can I retrieve the type in a clean way (I just read using getClass or instanceof is often not the best way).

*Sorry but I can't type closing braces

+1  A: 

Yes, instanceof isn't very clean. Sounds like goForIt() should change behavior depending on some property of the subclass. Instead of hard-coding the question to be "is it an A?", make the question "does the class have some key property Foo?" (which A has, presumably). And then, make the classes answer the question.

public class C {
  public abstract boolean isFoo();
  public void goForIt(C c) {
    if (isFoo()) {
      ...
  }
  ...
}

public class A extends C {
  public boolean isFoo() {
    return true;
  }
  ...
}

public class B extends C {
  public boolean isFoo() {
    return false;
  }
  ...
}
Sean Owen
+2  A: 

The clean way is not to "retrieve the type" explicitly at any point.

Instead, you make goForIt() a method of class C and have A and B override it and implement it differently, possibly calling super.goForIt() in the process.

Michael Borgwardt