class HouseLee {
String lastname = "lee";
}
public class Sample {
public static void main(String[] args) {
HouseLee lee1 = new HouseLee();
HouseLee lee2 = new HouseLee();
}
}
이처럼 HouseLee 클래스를 만든 후 객체를 생성하면 객체마다 lastname을 저장하기위한 메모리를 별도로 할당한다.
하지만 어차피 lastname의 값은 lee이어야 한다면 static을 사용해 메모리 낭비를 줄일 수 있다.
class HouseLee {
static String lastname = "lee";
}
public class Sample {
public static void main(String[] args) {
HouseLee lee1 = new HouseLee();
HouseLee lee2 = new HouseLee();
}
}
이처럼 static을 앞에 쓰면 메모리 할당을 한번만 하여 메모리 낭비를 줄일 수 있다.
또한 static을 사용하는 이유는 값을 공유하기 때문이다. static을 설정하면 같은 메모리 주소를 바라보기때문에 static변수의 값을 공유할 수 있다.
class Counter{
int counter = 0;
Counter() {
this.counter++;
System.out.println(this.counter);
}
}
public class Sample {
public static void main(String[] args) {
Counter counter1 = new Counter();
Counter counter2 = new Counter();
}
}
이 코드를 실행해보면 각 1의 값이 출력된다. c1,c2의 객체를 생성할 때 다른 메모리 주소를 가지기 때문에 값이 공유되지 않는다.
class Counter{
static int count = 0;
Counter() {
count++;
System.out.println(count);
}
}
public class Sample {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
}
}
하지만 static을 count변수 앞에 붙여주게된다면 count의 값이 공유되어 결과는 1,2가 된다. 변수에 쓰이는 static키워드는 값의 공유를 위해서 많이 사용된다.
2. static 메서드
class Counter{
static int count = 0;
Counter() {
count++;
System.out.println(count);
}
public static int getCount() {
return count;
}
}
public class Sample {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(Counter.getCount());
}
}
Counter 클래스에 getCount()라는 스태틱 메서드를 추가했다. 메서드 앞에 static 키워드를 붙이면 Counter.getCount()와 같이 객체 생성 없이도 클래스를 통해 메서드를 직접 호출할 수 있다.
***스태틱 메서드 안에서는 객체 변수 접근이 불가능하다. 이 예에서는 count 변수가 static 변수이기 때문에 스태틱 메서드에서 접근이 가능하다.***
'JAVA 기초공부' 카테고리의 다른 글
| Jump to Java - 8장 프로그래밍 예제 (1) | 2025.02.18 |
|---|---|
| JAVA - 예외처리, try - catch문 (0) | 2025.02.17 |
| JAVA - 접근제어자 (0) | 2025.02.15 |
| JAVA - package (0) | 2025.02.15 |
| JAVA - 콘솔 입출력 (1) | 2025.02.06 |