java - Good design for accessing subclass methods in a vector of abstract class objects -
i using vector store objects of anabstractclass
superclass. abstract class contains 2 non-constructor methods:
public final string getname() { return name; } public abstract int getcost();
within each subclass created getcost
method. within anotherclass
have vector of abstract class objects. in method of anotherclass
using string contains name, cost, , other data types specific each of multiple subclasses. accessing vector retrieve name
, cost
fine.
however, when try access other fields (ie: getcolor
or getsize
specific each subclass run following compile error:
error: cannot find symbol symbol: method <mysubclassmethod>() location: class <myabstractclass>
how can efficiently design solution dilemma?
to access methods specific subclass need cast subclass.
example:
subclass foo = (subclass) myanabstractclassinstance;
if don't know subclass have, can type check using instanceof
example
// subclass implements size , color, superclass not if (foo instanceof subclass) { subclass foobar = (subclass) foo; int size = foobar.size(); string color = foobar.color(); }
alternative solutions: 1. make subclasses provide methods (even if nothing) 2. make subclasses provide method lets know methods support
Comments
Post a Comment