Parameter passing, local variables, and return values
Main class (in ParameterPassingTest.java)
class ParameterPassingTest{
public static void main(String args[]) {
Dog fido, spot, rover;
int x, y;
fido = new Dog("Fido");
spot = new Dog("Spot");
x = 6;
y = 8;
fido.addTrick();
school1(fido, x);
school2(spot, x);
fido = createSuperdog(spot, 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("Fluffy");
dog.train(n);
}
public static Dog createSuperdog(Dog origDog, int x) {
String name = origDog.getName() + " the Clever Canine";
int numTricks = origDog.getTricks() + x;
Dog superDog = new Dog(name);
superDog.train(numTricks);
return superDog;
}
public static int mystery(int x) {
int y = 5 + x;
x = y / 3;
return x;
}
}
Dog class (in Dog.java)
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++; // Note: this is the same as tricks = tricks + 1
}
public void train(int n) {
tricks += n; // Note: this is the same as tricks = tricks + n
}
}