【发布时间】:2016-04-11 03:02:09
【问题描述】:
在通过父/抽象类处理对象时,如何访问子类而不是抽象类的属性?就像在这个例子中一样:
public class WordCategories {
public static abstract class Noun {
public static final String TYPE = null;
//... and so on, methods
}
public static class Person extends Noun {
public static final String TYPE = "Person";
// ...
}
}
/* ... then we build a collection with members like: */
nouns.add(new WordCategories.Person("Bill Clinton");
/* now later we need to access a mixed list of nouns: */
for(WordCategories.Noun n: nouns) {
if(n.TYPE.equals("Person") ){ // this is always null
}
显然我可以指定(WordCategories.Person) n,但这假设它是一个人。我需要来自父类的演员表,如果它不涉及解释 TYPE 常量或使用反射,那将是最优雅的。
【问题讨论】:
-
机器人错了这不是字符串比较问题
-
@hovercraft 我不这么认为。这是关于从父类表达式访问子类中的静态字段。
-
@Pillar:也许吧,但他的原始帖子,在“bot”评论和编辑之前,显示明显不正确的字符串比较。
-
是的,我编辑了它.. 谢谢。我当场做了例子。我的实际问题是我通过假设类变量是可访问的来获得空指针引用..并且它 is ,我可以在调试器中看到它。但是当它被转换为抽象类时我无法访问它。
-
@HovercraftFullOfEels 也许是,但他们正在比较字符串常量,所以它们可能是相等的,也许是有意的。