inheritance - Is there a good trick for instantiating a subclass with an instance of its superclass? -
preferably in java, there way instantiate subclass instance of superclass?
say have classb subclasses classa, here constructor classa:
public classa(){ }
i want like:
public class classb extends classa{ public classb(classa aclassa){ super(aclassa); } }
is there way instance of subclass instance of superclass, when subclass might have 1 field superclass, , therefore there isn't difference between them?
for instance,
classa = new classa();
classb b = a;
(the compiler going want me this: classb b = (classb)a;
... not going work.)
how do this?
is there way instance of subclass instance of superclass
no , superclass instance doesn't contain subclass instance . trying cast object referenced superclass type reference variable object of subclass.
classb b = (classb)a;
it dangerous , may fail if a
didn't refer instance of classb
@ run time.
remember instances of classb
instanceof classa
, reverse not true.
i not sure trying achieve , may @ abstract factory pattern , factory method pattern , see if helps.
Comments
Post a Comment