书中提到:

    • Java 程序设计语言总是采用按值调用

    基本类型:

    image.png

    引用类型:

    image.png

    这种行为与 Go 类似. 主要要区分基本类型和引用类型.

    书中举了例子来说明常见的错误: Java 方法参数是引用类型

    image.png

    • 方法内部的交换对外层不起作用

    image.png

    自己写的测试用例:

    1. package chapter04;
    2. import java.time.LocalDate;
    3. import java.util.Objects;
    4. public class Employee {
    5. private String name;
    6. private double salary;
    7. private LocalDate hireDay;
    8. public Employee(String n, double s, int year, int month, int day) {
    9. name = Objects.requireNonNull(n, "The name cannot be null");
    10. salary = s;
    11. hireDay = LocalDate.of(year, month, day);
    12. }
    13. public String getName() {
    14. return name;
    15. }
    16. public static void Exchange(Employee x, Employee y) {
    17. Employee tmp = x;
    18. x = y;
    19. y = tmp;
    20. }
    21. }
    22. public class Main {
    23. public static void main(String[] args) {
    24. Employee employee1 = new Employee("abc", 123.03, 2021, 4, 28);
    25. Employee employee2 = new Employee("def", 123.03, 2021, 4, 28);
    26. Employee.Exchange(employee1, employee2);
    27. System.out.println(employee1.getName()); // abc
    28. System.out.println(employee2.getName()); // def
    29. }
    30. }

    如果非要实现对外层进行交换, 那么参数的类型应该是 指针的指针,