How do I recover the actual type of the this object in a class hierarchy?
Hi,
This is code snippet from Angelica Langer's FAQ:
abstractclass Node <Nextends Node><N>>{
privatefinal List<N> children =new ArrayList<N>();
privatefinal N parent;
protected Node(N parent){
this.parent = parent;
if(parent!=null)
parent.children.add(this);// error: incompatible types
}
public N getParent(){
return parent;
}
public List<N> getChildren(){
return children;
}
}
There are 3 different approaches available in the FAQ to solve this problem.
My question is:
If I write:
...
parent.children.add((N)this);// cast added here
...
as described at the end of this topic in the FAQ, am I safe here (despite
the compilers warning) ? In my opinion, although I understand that
compiler needs to issue a warning, it is actually 100% safe .... or is it not ?
Or let's ask more precise question: can it throw a ClassCastException at
runtime ever ? If so, can you give any example ?
Thanks,
Adrian

