멘토링

static Keyword in Java

langsamUndStetig 2022. 6. 13. 17:56

자바에서의 static Keyword를 알아보자!

 

자바에서 static keyword가 가지는 의미

- 타입의 객체가 아니라 타입에 직접적으로 연관된 멤버, 즉 클래스의 모든 객체가 공유하는 멤버

- varaiable, method, block, 그리고 nested  class에 static keyword를 붙일 수 있다.

 

Static Field( Class Variable) 

- 메모리적 관점에서 보면 static variable은 힙 영역에 저장되어 있다.

- 객체와 독립적이거나 모든 객체에서 공유되어야 할 때 static variable 사용

- 클래스에 속해 있기 때문에 객체 생성 없이 사용할 수 있다.

- 클래스 수준에서만 static variable을 선언할 수 있다.

- 객체 참조를 통해서 (object1.static_variable_name) 접근할 수 있지만, 객체 변수인지 아닌지 헷갈려지기 때문에 안하는게 좋다.

 

 

public class Practice {
  int number;
  String name;
  static int count;

  Practice(int number, String name) {
    this.number = number;
    this.name = name;
    count++;
  }

  public int getNumber() {
    return number;
  }

  public String getName() {
    return name;
  }

  public static int getCount() {
    return count;
  }

  public String toString() {
    return "number= " + number + ", name= " + name + ", count= " + count;
  }
  public static void main(String[] args) {
    Practice a = new Practice(23, "Kim");
    Practice b = new Practice(23, "Kim");

    System.out.println(a); // number= 23, name= Kim, count= 2
    System.out.println(b); // number= 23, name= Kim, count= 2

    a.name = "Lee"; 
    a.number = 25;
   a.count = 20; // countsms Practice 클래스의 static variable이어서 
     		     // 객체의 모든 count 값이 변경되었음
                 // Class명으로 접근하는 게 더 좋음
    System.out.println(a); // number= 25, name= Lee, count= 20
    System.out.println(b); // number= 23, name= Kim, count= 20

Static Method (Classs Method)

- static variable과 비슷하게 Class에 속해 있어서, 객체 생성 없이 호출 가능하다.

- 객체와 독립적으로 사용하고 싶거나 클래스의 모든 객체에서 공유하고 싶을 때  static method 선언

- static variable과 다른 static 메서드에 접근하거나 조작하기 위해서 사용한다.

- utility class 와 helper class에서 많이 사용된다.

- static 메서드는 컴파일 할 때 진행되기 때문에, 실행시 적용되는 method overriding엔 사용될 수 없음.

- 추상 메서드는 static 메서드가 될 수 없음

- static 메서드는 this나 super keyword를 사용할 수 없다. 

- instance variable과 instance 메서드는 static variable과 static 메서드를 사용할 수 있으나, 그 반대는 불가능하다. 왜냐하면 static 변수와 메서드는 class가 메모리에 올라올 때부터 생성되어서 끝날 때까지 존재하지만, instance는 객체 생성시에만 나오기 때문이다.

 

Static Block

- static variable을 초기화하기 위해서 사용한다. 선언할 때 직접 static variable을 초기화할 수 있지만, 멀티라인 프로세싱이 필요한 상황에 static block을 사용한다.

- List 객체의 초기 값을 설정해줄 때 사용가능하다.

- static variable을 초기화하는게 오류가 나기 쉽고, exception을 다뤄야 할 때.

- 한 클래스는 여러개의 static block을 가질 수 있다.

- static field와 static block은 동일한 순서로 실행된다.

ublic class Practice {
  public static List<String> greet = new LinkedList<>();

  static {
    greet.add("Hi");
    greet.add("Hello");
    greet.add("Hey");
    greet.add("Bye");
  }
}
  

Static Class

- Java는 내부 클래스를 허용한다. 내부에서 요소들을 묶어서, 코드를 더 정돈되고 읽기 쉽게 해준다.

- nested class 구조는 static nested class와 non-static class인 inner class로 구분된다.

* 이 두개의 차이점은 inner class는 외부 클래스의 private 멤버를 포함한 모든 멤버에 접근할 수 있지만, static nested class는 오직 외부 클래스의 static 멤버에만 접근 가능하다.

- 싱글톤 패턴에서 자주 사용된다.

- 한 곳에서만 쓰이는 클래스들을 묶는 것은 캡슐화를 증가시켜준다.

- 한 곳에 모아 두기 때문에 코드 가독성과 유지성이 더 좋아진다.

-  만약 내부 클래스가 외부 클래스의 인스턴스 멤버에 접근할 필요가 없을 경우, static nested class로 선언하는게 좋다. 왜냐하면, 외부클래스에 연결되지 않아서 힙 혹은 스택 메모리가 덜 사용되고, 따라서 더 최적화 되기 때문이다.

- static nested class에서 외부 클래스의 instance 멤버에 접근하기 위해선 객체의 참조를 통해서 접근해야 한다.

- private static 멤버를 포함한 모든 static 멤버에 접근할 수 있다.

- 최상위 클래스에선 static을 허용하지 않는다. 오직 내부 클래스만 static 클래스가 될 수 있다.

* 최상위 클래스는 public이나 기본만 허용한다.

 

 

 

참고 자료

https://www.baeldung.com/java-static

https://www.geeksforgeeks.org/static-keyword-java/