-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParamTest.java
85 lines (74 loc) · 2.37 KB
/
ParamTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package ParmTest;
/**
* This program demonstrates parameter passing in Java.
*
* @author Cay Horstmann
* @version 1.00 2000-01-27
*/
public class ParamTest {
public static void main(String[] args) {
/*
* Test 1: Methods can't modify numeric parameters
*/
System.out.println("Testing tripleValue:");
double percent = 10;
System.out.println("Before percent = " + percent);
tripleValue(percent);
System.out.println("After percent = " + percent);
/*
* Test 2: Methods can change the state of object parameters
*/
System.out.println("\nTesting tripleSalary:");
Employee harry = new Employee("Harry", 50000);
System.out.println("Before salary = " + harry.getSalary());
tripleValue(harry);
System.out.println("After: salary = " + harry.getSalary());
/*
* Test 3: Methods can't attach new objects to object parameters
*/
System.out.println("\nTesting swap");
Employee a = new Employee("Alice", 70000);
Employee b = new Employee("Bob", 60000);
System.out.println("Before a = " + a.getName());
System.out.println("Before b = " + b.getName());
swap(a, b);
System.out.println("After: a = " + a.getName());
System.out.println("After: b = " + b.getName());
}
// doesn't work
public static void tripleValue(double x) {
x = 3 * x;
System.out.println("End of method: x = " + x);
}
// works
public static void tripleValue(Employee x) {
x.raiseSalary(200);
System.out.println("End of method: salary = " + x.getSalary());
}
public static void swap(Employee x, Employee y) {
Employee temp = x;
x = y;
y = temp;
System.out.println("End of method: x = " + x.getName());
System.out.println("End of method: y = " + y.getName());
}
}
// simplified EmployeeTest class
class Employee {
private final String name;
private double salary;
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public void raiseSalary(double byPercent) {
double raise = salary * byPercent / 100;
salary += raise;
}
}