Java Classes - Using Public Methods to Obtain Private Fields (Page 3 of 5 )
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:
Modifier: public, private, protected, and package
Return type: the returned value's data type, or void if there is no value returned by the method
Method name: name of the method
Parameter: a list of input parameters, separated by commas, and preceded by data types. They are always enclosed in parentheses, unless there are no parameters, in which case you use two parentheses with nothing in between.
Exception Lists: discussed in a future issue
Method Body: the code of the method enclosed between braces.
Next: Naming Conventions for Our Pal, the Method >>
More Java Articles
More By James Payne