복제란
new 통해 데이터타입 생성 => 참조형 데이터타입
public class ReferenceDemo1 { 
public static void runValue() { 
int a=1; //1을 변수 a에 담음
int b =a; //a의 값 1을 변수 b에 담음
b=2; 
System.out.println("runValue, "+a); 
}}
//
runValue, 1
참조란
class A{ 
public int id; 
A(int id){ 
this.id = id; 
} 
} 
public class ReferenceDemo1 { 
public static void runValue() { 
int a = 1; 
int b = a; 
b= 2; // 1을 int a에 담음 -> 1을 복제해(결국 각각 다른 1의 값) b에 담음
System.out.println("runValue, "+ a); 
} 
public static void runReference() { 
A a = new A(1);  => 기본 데이터타입 (int) 변수값 - new 통해 만드는 데이터타입 변수값 다르게 작동
A b = a; 
b.id = 2; //A 인스턴스 생성됨 -> 1. 변수 a는 인스턴스의 위치 알게 됨 -> 2. 변수 b도 인스턴스 주소값 알게됨 -> 3. 인스턴스의 id값을 2로 변경 => 참조(인스턴스를 구분할 수 있는 주소값만 가짐)
System.out.println("runReference, "+a.id); 
} 
public static void main(String[] args) { 
runValue(); 
runReference(); 
}}
//
runValue, 1 
runReference, 2
참조 - 복제 비교

참조는 파일 바로가기 (바로가기 수정= 원본 수정)
복제는 파일 복사 붙여넣기와 유사
메소드의 매개변수와 참조, 복제
public static void runReference() { 
A a = new A(1); 
A b = a; 
b = new A(2);    //새로 참조할 인스턴스  => a 와 b는 다른 인스턴스를 참조함
System.out.println("runReference, "+a.id); 
}
//
runValue, 1 
runReference, 1
- ???이해어렵
 
static void _value(int b) { 
b=2; 
} 
static void runValue() { 
int a =1; 
_value(a); 
System.out.println("runValue, "+ a); 
} 
static void _reference1(A b) { 
b = new A(2); 
} 
static void runReference1() { 
A a = new A(1);   //참조, id값: 1
_reference1(a);    // A b = a, b = new A(2) => 새로운 변수 b가 만들어져 A (주소값 2) 참조
System.out.println("runReference1, "+a.id); 
} 
static void _reference2(A b) { 
b.id = 2; 
} 
static void runReference2() { 
A a = new A(1);   //변수 a가 인스턴스 참조
_reference2(a);    //A b = a, b.id = 2   => 변수 b는 a 참조 => a는 new A(1)
System.out.println("runReference2, "+a.id); 
} 
public static void main(String[] args) { 
runValue(); 
runReference1(); 
runReference2(); 
}}
//
runValue, 1 
runReference1, 1 
runReference2, 2
'Programming > 자바' 카테고리의 다른 글
| 생활코딩 자바 - Collections framework (0) | 2022.04.24 | 
|---|---|
| 생활코딩 자바 - 제네릭 (0) | 2022.04.20 | 
| 생활코딩 자바 - 상수2 - enum (0) | 2022.04.18 | 
| 생활코딩 자바 - Object 클래스 (0) | 2022.04.18 | 
| 생활코딩 자바 - 예외 (0) | 2022.04.12 |