Parameter passing, local variables, and return values
Main class (in ParameterPassingTest.java)
public class ParameterPassingTest{
public static void main(String args[]) {
Dog fido, spot, rover;
int x, y, z;
fido = new Dog("Fido");
spot = new Dog("Spot");
x = 6;
y = 8;
fido.addTrick();
school1(fido, x);
school2(spot, x);
spot = nextGeneration(fido, y);
y = mystery(x);
}
public static void school1(Dog dog, int n) {
dog.train(n);
}
public static void school2(Dog dog, int n) {
n = 4;
dog = new Dog("Rover");
dog.train(n);
}
public static Dog nextGeneration(Dog origDog, int x) {
String name = origDog.getName() + " II";
int numTricks = origDog.getTricks() + x;
Dog nextDog = new Dog(name);
nextDog.train(numTricks);
return nextDog;
}
public static int mystery(int x) {
int y = 5 + x;
x = y / 3;
return x;
}
}
Dog class (in Dog.java)
public class Dog {
private int tricks; // number of tricks the dog knows
private String name; // the dog's name
public Dog(String newName) {
tricks = 0;
name = newName;
}
public int getTricks() { return tricks; }
public String getName() { return name; }
public void addTrick() { tricks++; }
public void train(int n) { tricks += n; }
}