Java & J2EE Page 3 - Java Classes |
It is common practice to make member fields private. However, sometimes we still need access to the data they contain throughout our program. To retrieve this data, we can use methods, like so: public class BruceLee { private int punch; private int kick; private int roundhouse; public BruceLee(int doPunch, int doKick, int doRoundhouse) { punch = doPunch; kick = doKick; roundhouse = doRoundhouse; } public int gimmePunch() { return punch; }
public void determinePunch(int newPunch)) { punch = newPunch; } } public int gimmekick() { return kick; } public void determineKick(int newKick)) { kick = newKick; } } public int gimmeRoundhouse() { return roundhouse; } public void determineRoundhouse(int newRoundHouse)) { roundhouse = newRoundHouse; } } Declaring Methods A method declaration looks like this: public double decideWhoIsFatter(double yourWeight, int myWeight) { insert math here } The required parts of a method declaration are the return type, name, some parentheses(), and a body located between two braces{}. There are six possible parts of a method declaration:
blog comments powered by Disqus |
|
|
|
|
|
|
|