1. static 키워드
-
static
이 붙은 것들은 인스턴스 생성 없이 클래스명으로 접근해서 사용할 수 있다
- 공용의 개념으로 생각하면 이해가 편하다
- 정적 메서드(static method)
- 정적 변수(static variable)
2. 정적 변수(Static Variable)
정적 변수 소개
스태틱을 사용하는 경우와 사용하지 않는 경우
Data1
이라는 클래스를 하나 정의하자.
1
2
3
4
5
6
7
8
9
10
|
public class Data1 {
public String name;
public int cnt;
public Data1(String name) {
this.name = name;
cnt++;
}
}
|
static
을 사용하지 않는 경우 인스턴스를 생성하고, 참조변수.멤버변수
같은 형태로 사용해야 한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public class DataMain {
public static void main(String[] args) {
// 각 인스턴스를 새롭게 생성하고 인스턴스 멤버인 cnt를 접근하는 것(공유되지 않음!)
Data1 d1 = new Data1("d1");
System.out.println(d1.name+" count : "+d1.cnt);
Data1 d2 = new Data1("d2");
System.out.println(d2.name+" count : "+d2.cnt);
Data1 d3 = new Data1("d3");
System.out.println(d3.name+" count : "+d3.cnt);
}
}
|
1
2
3
|
d1 count : 1
d2 count : 1
d3 count : 1
|
StaticData1
이라는 static
을 사용하는 클래스를 만들어보자.
1
2
3
4
5
6
7
8
9
10
11
12
|
public class StaticData1 {
public String name;
public static int cnt; // static 붙음
public StaticData1(String name) {
this.name = name;
// 원래는 StaticData1.cnt++; 으로 static 변수를 사용하지만
// 같은 클래스 내에서는 생략 가능
cnt++;
}
}
|
인스턴스 생성 없이 클래스명을 통해서 사용할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public class StaticDataMain {
public static void main(String[] args) {
// 인스턴스 참조 변수로 접근하는 것이 아니라 클래스명을 이용해서 접근
StaticData1 d1 = new StaticData1("d1");
System.out.println(d1.name+" count : "+StaticData1.cnt);
StaticData1 d2 = new StaticData1("d2");
System.out.println(d2.name+" count : "+StaticData1.cnt);
// 인스턴스 참조 변수로 접근해도 가능은 하지만 권장하지 않음
// 인스턴스 멤버에 cnt가 없는 것을 확인 -> 메서드 영역의 static 변수에서 확인
StaticData1 d3 = new StaticData1("d3");
System.out.println(d3.name+" count : "+d3.cnt);
}
}
|
1
2
3
|
d1 count : 1
d2 count : 2
d3 count : 3
|
3. 정적 메서드(Static Method)
- 클래스 메서드라고도 부른다
- 인스턴스(객체) 생성 없이 호출 가능
- 인스턴스 멤버와 관련 없는 작업을 한다
- 단순히 기능만 제공하는 메서드면
static
사용을 고려하자
- 간단히 메서드로 끝낼수 있는 유틸리티성 기능들에 자주 사용된다
- 정적(
static
) 메서드는 static
이 붙은 애들만 사용 가능
1
2
3
4
5
6
7
|
public class StaticMethod1 {
// 메서드에 static이 붙음
public static String addDecoration(String str){
return "=========== "+str+" ===========";
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
|
public class StaticMethodMain {
public static void main(String[] args) {
String s = "This is the string value";
// 클래스명.메서드명 으로 접근
String result = StaticMethod1.addDecoration(s);
System.out.println(s);
System.out.println(result);
}
}
|
1
2
|
This is the string value
=========== This is the string value ===========
|
4. 정적 임포트(Static Import)
정적 임포트 사용시 경로를 붙이지 않고 바로 사용할 수 있다.
1
2
3
|
import static java.lang.Integer.*; // Integer 클래스의 모든 static 메서드
import static java.lang.Math.random; // Math.random() 만
import static java.lang.System.out; // System.out을 out으로 참조가능
|
- 인텔리제이
alt+enter
를 통해 Add on-demand static import
을 사용할 수 있다
Reference
- https://www.geeksforgeeks.org/java-memory-management/
- https://www.codelatte.io/courses/java_programming_basic/KUYNAB4TEI5KNSJV
Comments powered by Disqus.