public class SuperVertex extends Vertex{
int childAttr = 1;
}
public class Vertex {
int name = 0;
}
public class Test {
SuperVertex sv = new SuperVertex();
Vertex v = new Vertex();
HashMap<Vertex, Vertex> hmp = new HashMap<Vertex, Vertex>();
hmp.put(v,v);
hmp.put(sv,sv);
hmp.get(v).name //works
hmp.get(sv).name //works
hmp.get(sv).childAttr //doesn't work
}
如上所示代码我无法访问childAttribute,因为我从HashMap获取父类型对象。如何创建包含父类型和子类型对象并到达子对象属性的HashMap?
答案 0 :(得分:1)
(SuperVertex)hmp.get(sv).childAttr//works
投射到正确的类型可以解决问题。感谢@Miguel Gamboa和@nolexa。