Does a SubClass object in an ArrayList keep methods unique to SubClass?

前端 未结 3 794
无人及你
无人及你 2020-12-21 16:36

Basically what the title says, but some elaboration. I have a SuperClass with a couple of SubClasses. I needed an ArrayList to hold both types of Subclasses so hence the Arr

3条回答
  •  醉话见心
    2020-12-21 17:15

    All of the objects retain their own class identity, but the code that uses the ArrayList isn't directly aware of it. As far as it's concerned, the ArrayList only holds references to SuperClass-type objects, and it can only call SuperClass's methods on objects it retrieves from it.

    The calling code can use instanceof or similar techniques to find out if a particular object in a collection is of a subtype, but this is usually bad practice, since it usually indicates mixing of the different levels of abstraction. The one case where this is generally considered reasonable is if the subclass has some optional high-performance characteristic that the caller can take advantage of (and that measurement has determined is worth complicating the code for); one example might be that while List's get() method is has no performance guarantees, some implementations, like ArrayList, also implement RandomAccess, which indicates that there's no performance penalty to using get() in any order.

提交回复
热议问题