Cast element in Java For Each statement

前端 未结 5 2029
囚心锁ツ
囚心锁ツ 2021-02-19 00:30

Is it possible (or even advisable) to cast the element retrieved from a for each statement in the statement itself? I do know that each element in list will be of type <

5条回答
  •  梦毁少年i
    2021-02-19 01:00

    Possible, yes! but god forbid, Why? My early attempts in my career did that and I have learnt. Programming to interfaces always has an advantage. I always get questions from junior developers about handling cases where only subtypes have the methods/functionality required.

    Say Animal class with Dog subtype having method bark(). They want bark() functionality. The actual challenge is that they want a behaviour of animal communication not bark() but animal speak(). So a new Cat sub class would not require meow(). What about this then:- My dog's form a pack, but cats don't. The answer pack() behaviour is not owned by a single dog. Pack is a different aspect, pass a pack to all objects and ask the objects to join the pack. (Visitor pattern/Adapter pattern). My Wolf class can use the same behaviour.

    Am I rigid about this, no if it is only 1 off instance I am fine. If the answer is I am not sure, then you better play safe by working at interface contracts.

提交回复
热议问题