Java Reference
In-Depth Information
All we've done differently is specify what kind of value we're going to return
(
int
in this case) instead of using
void
in the declaration. Then we use the key-
word
return
with the value that we want to return to our caller. Usually you
want to call
return
as the very last thing in your function. That's because it
specifies what value to return
and
performs the return right then and there.
No more code will be run in your method after it hits the
return
. You're done.
Try This Yourself
Modify the
HashPlay.java
source so that no one's score can go below 0 or above
1,000. Use a helper function that returns a value to clamp the score to be
between 0 and 1,000.
You can see my solution in
HashPlayClamp/src/hashplay/HashPlay.java
. In fact, you
might see another subtle trick in there: instead of making the helper function
public
, I declared it to be
private
. What's that all about?
Keep Things Private or Make Them Public
So far, we've tended to use the Java keyword
public
when making static vari-
ables and defining functions and plugins. That tells Java that the thing we're
defining should be publicly accessible—all of our own plugin code can use it,
and any other plugin in the system can use it as well (like when we use
logger
).
There is another option. You can create functions or variables or even helper
objects that
no one else
can see. Instead of
public
, you can make them
private
.
In programming, there's a simple rule—so simple it's the kind of thing you'd
tell a five-year-old: don't expose your privates.
In other words, if you're using a function or something that
only
you should
use, then mark it as private to make sure that no one from the outside can
use it. Why would you need to do that?
Suppose that somewhere in your plugin you have a function to mark a player
as a super, high-level, über-Wizard. You wouldn't want any other plugin to
call that function on a player of its choosing. So where normally you'd declare
the function in the plugin like this (leaving out all the other bits):
public class
WizardingWorld
extends
EZPlugin {
...
public
void
makeSuperUberHighWizard(Player p) {
...
}
// Any other plugin can call WizardingWorld.makeSuperUberHighWizard()
}