我正在实现一个函数,并且将超类作为参数。
例如:
private void foo(Parent parent) {
if(parent.getClass() == Child1.class) {
Child1 c1 = (Child1) parent;
System.out.println(c1.getChild1Attribute());
}
else if(parent.getClass() == Child2.class) {
Child2 c2 = (Child2) parent;
System.out.println(c1.getChild2Attribute());
}
else if(parent.getClass() == Parent.class) {
System.out.println(parent.getParentAttribute());
}
}
这是一个不好的想法吗?
我在这里读到了一些帖子,说使用 getClass()
或 instanceof
是不好的设计:
if-instanceof
习惯用法。 - Marko Topolnik