What does this block of code do?

人盡茶涼 提交于 2019-12-02 07:27:16

问题


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

Player player = (Player) sender;

回答1:


It takes the object referenced by sender, and attempts to cast it into the type Player. Java objects are strongly typed, which means you have to declare the type of the object.

If the object referenced by sender cannot be cast to a Player object, than an exception will be thrown for an InvalidCast.




回答2:


That's a plain old java type cast. See the JLS Casting conversion for the full details.

It assumes that sender is type-compatible with a Player.




回答3:


It converts sender to a Player object. Otherwise, the datatype of player wouldnt match the datatype of sender. Usually done if sender could initially have been declared as a subclass.




回答4:


This is an assignment, with a cast operation.

You can learn a lot about java cast operator with the answers to this question: How does the Java cast operator work?




回答5:


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.




回答6:


this is a simple java typecast...

is this in a bukkit minecraft server plugin? if it is, what it does is typecast the player sending the command to a Player object. Player Objects are used to target specific players in code. the player object will have the name of the player who sent the command.



来源:https://stackoverflow.com/questions/6403368/what-does-this-block-of-code-do

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!