정적(Static)
- 프로그램을 실행하기 전 클래스 정의를 미리 읽어서 메모리에 얹는 작업
- **로딩 과정 중 만나는 모든 static 요소를 메모리에 구현함
- 지시자 (제어자) 중 하나임 .
- 클래스나 클래스의 멤버 앞에 붙임
- 모든 객체가 메모리를 공유함
- 즉 값을 공유할 수 있음
예시)
public class Ex1_Static {
public static void main(String[] args) {
Pen p1 = new Pen("MonAmi","Black");
Pen p2 = new Pen("MonAmi","Black");
Pen p3 = new Pen("MonAmi","Black");
System.out.println("총 볼펜 개수: " + Pen.count);
}//main
}
class Pen{
private String model;
private String color;
public static int count = 0; //누적변수 (펜 개수)
public Pen(String model, String color) {
this.model = model;
this.color = color;
}
public String dump() {
return String.format("[model: %s, color: %s"
,this.model
,this.color);
}
}
출력 결과는 0이다 분명 3개의 펜 객체를 생성하였는데 0 이 나오는데 static 값을 공유하여
class Pen {
public static int count = 0;
}
때문에 결과값이 0이 출력된다.
예시2)
public class Ex2_Static {
public static void main(String[] args) {
Pen p1 = new Pen("MonAmi","Black");
Pen p2 = new Pen("MonAmi","Black");
Pen p3 = new Pen("MonAmi","Black");
System.out.println("총 볼펜 개수: " + Pen.count);
}//main
}
class Pen{
private String model;
private String color;
public static int count = 0; //누적변수 (펜 개수)
public Pen(String model, String color) {
this.model = model;
this.color = color;
Pen.count++;
}
public String dump() {
return String.format("[model: %s, color: %s"
,this.model
,this.color);
}
}
정상적으로 3개 선언한 만큼 결과값이 출력되었다.
'java' 카테고리의 다른 글
| 상속(inheritance),Object 클래스 (2) | 2024.02.23 |
|---|---|
| 자바의 생성자(Constructor) (3) | 2024.02.20 |
| 자바의 접근 제어자 (Access) (1) | 2024.02.19 |
| 자바의 Class (1) | 2024.02.14 |
| 자바의 기본 성질 (1) | 2024.02.14 |