Re: cast to sub-class or extending instance of super or a.n.other
Richard Maher wrote:
I have an instance O of class A and I want to add a couple of attributes to
it and store it in an ArrayList. I don't want to (and can't anyway)
reconstruct O by sub-classing A and the super(o.x,o.y) and the JRE won't let
me cast O to a sub-class of A (unless that was the original constructor
used)
At the moment I have a new class B that has variable instance of A and
instances of my other stuff, but in the ArrayList I only want to
remove(),contains() and so on, purely on the instance of A. I can override
the equals() and hashCode() methods in B to only check against A and ignore
the other stuff but ArrayList.mostMethods(o2) tend to use the o2.equals(E)
approach which isn't helpful.
As I said this has gotta be easier than this so please put me out of my
misery. What's the best way of "new O = instance of A + stuff. Then still
behave like A in Arrays/Collections) Or is there something more appropriate
than ArrayList?
You should be able to get it to work if you sub class.
But delegation will not work. Just because B delegates methods
to A does make it an A.
If A implements an interface then B could implement the same
interface and there may be some possibilities.
Arne