호비시의 끄적끄적
Java Static, Final 본문
Static
선언
class StaticSample{
// non - static 필드, 메소드
int n;
void g() { ... }
// static 필드, 메소드
static int m;
static void f() { ... }
}
특성
static 멤버는 클래스당 하나만 생성되는 멤버로서, 동일한 클래스의 모든 객체들이 공유한다.
non-static 멤버는 객체가 생길 때 함께 생성되고, 객체가 사라지면 함께 소멸된다.
그러나 static 멤버는 프로그램을 시작할 때나 클래스 로딩 시에 생성된다.
그러므로 객체를 생성하기 전에 staic 멤버를 사용할 수 있다.
또한 생성된 객체가 소멸 후에도 static 멤버는 여전히 살아 있으며, 프로그램이 종료할 때 함께 소멸된다.
static method 의 제약 조건
- static method 는 오직 static 멤버만 접근할 수 있다.
class StaticMethod{
int n;
void f1(int x) {n=x;}
void f2(int x) {m=x;}
static int m;
static void s1(int x) {n=x;}
// 컴파일 오류. n이 non-static 필드인데, static method에서 사용하려 했기 때문.
static void s2(int x) {f1(3);}
// 컴파일 오류. f1이 non-static 필드인데, static method에서 사용하려 했기 때문.
static void s3(int x) {m=x;}
static void s4(int x) {s3(3);}
}
- static method 에서는 this를 사용할 수 없다.
static void f() { this.n = x;}
// 오류. static method 에서는 this 사용 불가능
final
final의 용도는 3가지이다.
- final 클래스
final이 클래스 앞에 사용되면 클래스를 상속받을 수 없음을 지정한다.
final class FinalClass{
...
}
class SubClass extends FinalClass{ // 컴파일 오류
...
}
- final 메소드
final이 메소드 앞에 붙으면, 이 메소드는 더이상 오버라이딩 할 수 없음을 지정한다. 자식클래스가 부모클래스의 특정 메소드를 오버라이딩 하지 못하게 하고 무조건 상속받아 사용하도록 하길 원한다면 final로 지정하면 된다.
public class SuperClass{
protected final int finalMethod(){ ... }
}
class SubClass extends SuperClass{
protected int finalMethod() { ... } // 컴파일 오류. 오버라이딩 할 수 없음
}
- final 필드
final로 필드를 선언하면 필드는 상수가 된다.
public class FinalFieldClass{
final int ROWS = 10;
void f(){
int[] map = new int[ROWS]; // 상수로 활용
ROWS = 30;// 컴파일 오류
}
}
'Back > Spring' 카테고리의 다른 글
Singleton Pattern (0) | 2022.07.17 |
---|---|
Spring Security (0) | 2022.07.10 |
Stream (0) | 2022.07.03 |
Lombok ? (0) | 2022.06.28 |
POJO 란? (0) | 2022.06.23 |
Comments