Java - array of different objects that have the same method(s)

前端 未结 4 1082
一生所求
一生所求 2020-12-17 05:57

I am practicing inheritance.

I have two similar classes that I\'d like to assimilate into one array, so I thought to use the Object class as a superclass since ever

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-17 06:16

    You need to typecast your object references to appropriate class to call their method..

    For each reference you fetch from your array, you need to check using instanceof operator, of which is the instance referred to by your object reference.. Accordingly you can typecast the reference to that class..

    But Typecasting is an ugly thing.. You should avoid it as far as possible.. If you have to choose which method to invoke based on exact sub class, you should probably go with an Interface.. It is the best way you can achieve what you want here...

    And I think you have got enough information about how to implement it..

提交回复
热议问题