开发者

Java method: retrieve the inheriting type

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开发者_如何学C 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*


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜