[01] static 변수(정적 변수, 클래스 변수), static method(클래스 메소드)
- static 변수와 메소드는 new를 이용해 객체를 만들지 않고 사용 가능합니다.
. 기본적으로 모든 클래스의 사용은 new를 이용하여 할당한 후 가능합니다.
- static 변수는 JVM으로 로딩시에 메모리에 오로지 하나만 생성됨으로
클래스 변수라고 합니다.
- '클래스명.변수명', '클래스명.메소드명'으로 접근합니다.
- static 변수는 최초 사용 요청시 한번만 메모리 할당을 받습니다.
1. static 변수는 객체를 만들지 않아도 접근할 수 있습니다.
>>>>> Scjp.java
class ScjpPass{
// 멤버 변수, 인스턴스 변수, 필드
int t1=0;
int t2=0;
// 클래스 변수, static 변수
static int BONUS=100;
// 기본 생성자 수동 정의
public ScjpPass(){
}
// 생성자
public ScjpPass(int t1, int t2){
//멤버 변수 = 지역 변수
this.t1 = t1;
this.t2 = t2;
}
}
public class Scjp {
public static void main(String[] args) {
// static 변수 사용, 객체를 생성하지 않습니다.
System.out.println("ScjpPass.BONUS: " + ScjpPass.BONUS);
ScjpPass sp = new ScjpPass(85, 90);
System.out.println("sp.t1: " + sp.t1);
}
}
2. static 메소드는 객체를 만들지 않고도 호출할 수 있습니다.
- wrapper 클래스에서 많이 사용되며 단순 기능만을 사용할 경우 구현합니다.
>>>>> SCWCDmain.java
class SCWCD{
int t1=0;
int t2=0;
static int BONUS=100;
public SCWCD(){
}
//클래스 메소드, static 메소드, 정적 메소드
public static void prLine(){
System.out.println("****************");
System.out.println(" ITWILL ");
System.out.println(" JAVA ");
System.out.println("****************");
}
}
public class SCWCDmain {
public static void main(String[] args) {
//클래스.static 메소드명
SCWCD.prLine();
}
}
3. 객체를 생성하면 멤버변수는 전부 기본값이나 생성자에서 지정한 값으로 초기화됩니다.
하지만 static변수는 프로그램을 실행시 최초 한번만 특정값으로 초기화되고
더이상 초기화가 되지않습니다.
따라서 한번 만들어진 static변수는 계속적으로 값이 증가 및 감소됩니다.
- static 변수는 객체를 여러번 생성해도 한번만 생성이 됩니다.
- static 변수는 멤버 메소드안에 선언 할 수 없습니다.
>>>>> StaticDemo.java
class Box {
int cnt = 0; // Attribute, 속성, 멤버 변수, 인스턴스 변수
//static 변수는 객체를 아무리 생성해도 1회만 초기화 됩니다.
static int boxID = 0;
// 기본 생성자
public Box() {
cnt = cnt + 1; // member variable
boxID = boxID + 1; // static variable
System.out.println("멤버 변수 cnt: " + cnt);
System.out.println("static 변수 BoxID: " + boxID );
}
}
public class StaticDemo {
public static void main(String args[]) {
Box box = null;
while(true){
box = new Box();
if (Box.boxID == 3){
System.out.println("객체는 메모리 문제로 3개만 생성 가능합니다.");
break;
}
}
}
}
4. static 의 활용 분야
- static 변수
. 객체간에 값을 공유할 경우 사용합니다.
. 상수 선언시에 사용합니다.
. 객체를 하나만 생성하는 singleton pattern의 구현에 사용됩니다.
- static 메소드
. 단순한 값의 변화를 구현시에 사용합니다. wrapper클래스 참고
Integer ii = new Integer()
Integer.parseInt("");
. 유틸리티(단순 데이터 조작) 클래스 제작에 사용됩니다.
[02] 값을 변경할 수 없는 final 변수(상수 선언)
- 값을 변경할 수가 없습니다.
- 값을 고정할 필요가 있는 코드와 같은 형태의 데이터에 사용합니다.
예)1년 12달, 요일, 주7일
>>>>> Finalmain.java
class Final{
int money = 10000; //인스턴스 변수
//값을 변경 할 수 없습니다., 상수, final 인스턴스 변수
final int day = 7; //1주
final int week = 4; //한달
//값을 변경할 수 없고 객체를 만들지 않아도 사용할 수 있습니다.
//final static 변수, static 상수
final static int month = 12; // 12 달
//생성자가 존재 하지만 아무런 처리를 하지 않습니다.
public Final(){}
}
public class Finalmain {
public static void main(String[] args) {
Final fi = new Final();
fi.money = 15000; // 변경 가능
// final변수는 값을 변경(대입)할 수 없습니다.
// fi.day = 10;
System.out.println("1주일 용돈:" + fi.money * fi.day);
System.out.println("1년" + Final.month + "달");
// Final.month = 20000;
}
}