티스토리 뷰

JAVA

static in Java

seoca 2019. 1. 5. 06:53


static 의 특징

- Static method는 클래스의 특정 객체가 아닌 클래스 자체에 속해있다.  

- static은 class가 load될 때 단 한번 실행된다.

- You can use a class name to call the static method.

- To access "static" we don't need an object.

static method는 instance 생성을 하지 않아도 접근 할 수가 있는 반면에 non-static method는 인스턴스 생성을 통해서만 접근 가능 하다. 


* 별도 메모리공간에 할당되어 초기화까지 완료가 된다. 그렇기에 인스턴스를 생성하지 않아도 호출이 가능



When do we use the Static method?

- If the static method is never changed or overridden. 

그 메소드가 절대 변경되지 않거나 overriding 되지 않을때

- You want the method accessible easily from other methods. 

다른 메소드와 쉽게 공유될 수 있게 하고 싶을 때



static variable 이란?

There is only one copy of a variable of a particular class. 

static variable 은 한 class 안의 모든 객체들과 공유되어질 수 있으며, 한 클래스의 객체 안에서 변하지 않을 변수에 static을 붙여준다. 



결론

결국 자바에서 static 이란 키워드는 method와 variable 을 포함해서 다른 method 혹은 variable과 공유할 수 있게 하거나(Static과 instance는 존재의 경계가 다르다), 변경되는 것을 원하지 않을 때 사용된다. 

인스턴스 변수에 저장된 값을 변경하거나 참조하는 일이 없다면 static으로 선언. 

이런 특징을 기반해서 Java design pattern 중에서 Sington pattern 을 이해 할 수 있다.

단, 너무 과도한 사용은 객체지향적이지 않은 프로그램으로 만들 수 있기 때문에 주의해야한다. 






Reference 

https://stackoverflow.com

난 정말 자바를 공부한 적이 없다구요 - 윤성우 저


'JAVA' 카테고리의 다른 글

String methods in Java  (0) 2019.01.07
Java Generics (runtime error,compile error)  (0) 2019.01.06
Overloading in Java with simple example  (0) 2019.01.04
Overriding in Java with an simple code  (0) 2019.01.04
super keyword  (0) 2019.01.03