Language/Java

[Java] static, final, static final의 차이

yujindonut 2023. 4. 24. 16:12
728x90

Static : 고정된

객체 생성 없이 사용할 수 있는 필드와 메소드를 생성하고자 할때 사용한다.

공용 데이터에 해당하거나, 인스턴스 필드를 포함하지 않는 메소드를 선언하고자 할때 이용한다.

this -> 인스턴스 필드나 메소드는 this 키워드를 사용할 수 있는데, static은 this키워드 사용불가

 

public class PlusClass {
	static int num = 10;
    static int plusMethod(int x, int y) {return x + y;}
    
	static int constructor (int x, int y) {
	this.num = x; // 이렇게 사용X
    this.plusMethod(); // 사용불가
    plusMethod(); // 사용가능
}
}

//main
int answer = PlusClass.plusMethod(15,2);
int answer2 = PlusClass.num + 2;

 

final : 최종적인

해당 변수는 값이 저장되면 최종적인 값이 되므로 수정이 불가능하다.

선언과 동시에 값을 줄 수 있고, 생성자로 생성할때 public 생성자로 값을 줄 수 있다.

// final 변수
final class Point {
	private static final int x = 2;
	private static final int y;
	public Point(int y) {
		this.y = y;
	}
}

// final method
// final 메소드는 오버라이디을 못한다(재정의)
class Test{
	public final void test2(){
		//내용정의
	}
}
public class Main extends Test{
	public test2(){} compile error: final method는 오버라이딩 못함
}

//final class
final class Test{
 int test;
}
//class Main extends Child{} final class는 상속할 수 없다

 

static + final :  (고정된 최종적인) 상수를 선언

해당 값은 객체마다 저장될 필요가 없으며, 여러값을 가질 수 없다.

클래스의 모든 인스턴스에 대해 동일한 값을 설정할 때, static final을 사용한다. 

728x90