java方法参数_Java方法参数的传递方式

48304ba5e6f9fe08f3fa1abda7d326ab.png

1 public class ParamTest {

2 public static void main(String[] args) {

3 /*

4 *Test1: Methods can't modify numeric parameters

5 */

6 System.out.println("Testing tripleValue:");

7 double percent = 10;

8 System.out.println("Before: percent=" + percent);

9 tripleValue(percent);

10 System.out.println("After: percent=" + percent);

11

12 /*

13 *Test2: Methods can change the state of object parameters

14 */

15 System.out.println("\nTesting tripleSalary");

16 Employee harry = new Employee("Harry", 50000);

17 System.out.println("Before: salary=" + harry.getSalary());

18 tripleSalary(harry);

19 System.out.println("After: salary=" + harry.getSalary());

20

21 /*

22 *Test3: Methods can't attach new objects to object parameters

23 */

24 System.out.println("\nTesting swap");

25 Employee a = new Employee("Alice", 30000);

26 Employee b = new Employee("Bob", 60000);

27 System.out.println("Before: a=" + a.getName());

28 System.out.println("Before: b=" + b.getName());

29 swap(a, b);

30 System.out.println("After: a=" + a.getName());

31 System.out.println("After: b=" + b.getName());

32 }

33

34 public static void tripleValue(double x) {

35 x *= 3;

36 System.out.println("End of method: x=" + x);

37 }

38

39 public static void tripleSalary(Employee x) {

40 x.raiseSalary(200);

41 System.out.println("End of method: salary=" + x.getSalary());

42 }

43

44 public static void swap(Employee x, Employee y) {

45 Employee temp = x;

46 x = y;

47 y = temp;

48 System.out.println("End of method: x=" + x.getName());

49 System.out.println("End of method: y=" + y.getName());

50 }

51 }

52

53 class Employee {

54 private String name;

55 private double salary;

56 public Employee(){}

57 public Employee(String name, double salary){

58 this.name = name;

59 this.salary = salary;

60 }

61

62 public String getName() {

63 return name;

64 }

65

66 public double getSalary() {

67 return salary;

68 }

69

70 public void raiseSalary(double byPercent){

71 double raise = salary * byPercent / 100;

72 salary += raise;

73 }

74 }

48304ba5e6f9fe08f3fa1abda7d326ab.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值