What does this block of code do?

后端 未结 6 979
鱼传尺愫
鱼传尺愫 2021-01-24 13:19

I\'m not quite sure what this means or whats it doing, Could some one elaborate?

Player player = (Player) sender;
6条回答
  •  时光说笑
    2021-01-24 13:47

    When you read it 'converts' sender to Player, don't think it literally converts them.

    There are many times where you pass a variable which COULD be many different things, then when you figure out what thing it is, you use the cast operator to actually MAKE one of those things.

    Heres a imperfect analogy:

    Imagine you get a phone call from your local computer club president, he says that a member of the club will be coming to see you about something.

    Now, you don't know which member is coming, if its female or male, how old or even their name, you know nothing about the future visitors attributes.

    Once they appear at your door, you realize its your buddy Frank, now in your mind, the 'visitor' (sender) from code above, is CAST to 'Frank', who you know lots of stuff about, age, how many kids, address etc.

    Before the CAST, you knew very little about the sender, but after the cast you can now access all kinds of info on the new Object, since you now know its TYPE.

    Hope this helps.

提交回复
热议问题