JAVA
static 에 관하여
방금시작한사람
2019. 12. 22. 00:04
Static => 정적 멤버
Static 이 붙은 변수나 메소드는 객체가 만들어지기 전에도 호출하여 사용할 수 있다.
class A{
public static int staticValue = 10;
public static void staticMethod(){
System.out.println("Static Method");
}
}
public class Main {
public static void main(String[] args) {
System.out.println(A.staticValue); // 10
A.staticMethod(); // Static Method
}
}
위처럼 A라는 클래스가 있지만 A라는 클래스를 가지고 만든 객체가 없어도 사용할 수 있다.
그리고 Static Method는 A가 만들어지기 전에 호출하는 것이기 때문에
A 관련된 변수(static 변수 제외)나 함수를 넣을 수 없다.
왜냐면 객체가 만들어져야 사용할 수 있는데, 객체가 없어도 사용할 수 있는 것이 static 이기 때문
class A{
public static int staticValue = 10;
public int a;
public static void staticMethod(){
System.out.println(staticValue); // 가능
this.a = 10; // compile error
sayHello(); // compile error
}
public void sayHello(){
System.out.println("hello");
}
}
그래서 static 을 사용할 때는 모든 객체가 공통적으로 사용하는 함수나 변수가 붙이면 좋다고 한다.
예시로는 우리가 매일 사용하는 static void main 이 있다.
만약 static 이 아니라면 main 함수는 main 함수를 가진 클래스를 생성한 뒤 실행되어야 할 것이다.
public static void main(String[] args) {
System.out.println(A.staticValue);
A.staticMethod();
int value = Math.max(10, 20);
}
그리고 자주 사용하는 Math 클래스의 메소드가 다 static 으로 되어있다.
public static int max(int a, int b) {
return a >= b ? a : b;
}
그래서 사용할 때는 int maxValue = Math.max(10, 20);
이렇게 바로 사용할 수 있는 것이다.
참고로 Math 클래스는 생성자가 private 지정되어 객체를 생성할 수 없다..