09. 기술면접 - 자바 - 자바는 항상 CallByValue 이다
공부목적으로 다른 블로그의 글을 그대로 따라치면서 작성되었습니다. 저작권 문제 시, 비공개 처리하겠습니다

public class CallByVal { public static void main(String[] args) { Person admin = new Person(1L, "admin"); changePerson(admin); System.out.println(admin); } private static void changePerson(Person admin) { admin = new Person(2L, "root"); } } class Person { private Long id; private String name; public Person(long id, String name) { this.id = id; this.name = name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + '}'; } }

public class CallByVal { public static void main(String[] args) { Person admin = new Person(1L, "admin"); changePerson(admin); System.out.println(admin); } private static void changePerson(Person admin) { admin.setName("root"); } } class Person { private Long id; private String name; public Person(long id, String name) { this.id = id; this.name = name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + '}'; } }

여기서 값(value) 란?
-> 기본자료형의 값 또는 객체에 대한 레퍼런스
-> 즉, Person 도 값이라고 생각해야된다
-> 그래서 파리미터 admin = new Person() 을 해도 main 에서의 admin 변수는 변하지 않았다
-> 파라미터 admin 에는 복사한 값(refernce 타입)이 들어가 있지만, setName과 .name 은 원본 인스턴스의와 참조
(연결) 되어 있다. 때문에 .name 과 setName() 을 통해 원본 인스턴스가 바뀌게 되는 것 이다
참고
GitHub - WeareSoft/tech-interview: 🙍 tech interview
:loudspeaker:🙍 tech interview. Contribute to WeareSoft/tech-interview development by creating an account on GitHub.
github.com
이 글은
(새창열림)
본 저작자 표시 규칙 하에 배포할 수 있습니다. 자세한 내용은 Creative Commons 라이선스를 확인하세요.
Creative Commons
본 저작자 표시
'∞. 기술 면접 > 7. 자바' 카테고리의 다른 글
| 11. 기술면접 - 자바 - 컬렉션 프레임워크 (Collection Framework) (0) | 2021.10.21 |
|---|---|
| 10. 기술면접 - 자바 - 인터페이스와 추상 클래스 차이 (0) | 2021.10.21 |
| 08. 기술면접 - 자바 - 직렬화(Serializable) (0) | 2021.10.21 |
| 07. 기술면접 - 자바 - 가비지 컬렉션(Garbage Collection ) 처리 방법 (0) | 2021.10.21 |
| 06. 기술면접 - 자바 - Non Static 과 Static (0) | 2021.10.21 |
댓글
이 글 공유하기
다른 글
-
11. 기술면접 - 자바 - 컬렉션 프레임워크 (Collection Framework)
11. 기술면접 - 자바 - 컬렉션 프레임워크 (Collection Framework)
2021.10.21 -
10. 기술면접 - 자바 - 인터페이스와 추상 클래스 차이
10. 기술면접 - 자바 - 인터페이스와 추상 클래스 차이
2021.10.21 -
08. 기술면접 - 자바 - 직렬화(Serializable)
08. 기술면접 - 자바 - 직렬화(Serializable)
2021.10.21 -
07. 기술면접 - 자바 - 가비지 컬렉션(Garbage Collection ) 처리 방법
07. 기술면접 - 자바 - 가비지 컬렉션(Garbage Collection ) 처리 방법
2021.10.21
댓글을 사용할 수 없습니다.