[ JAVA ] static은 무엇인가?

행복한 콩🌳·2022년 12월 22일
0

JAVA

목록 보기
11/26

JAVA하면 아무 생각 없이 치는

public static void main(String[] args){}

여기서 저 static은 무엇일까

static - class method
no static - instance method

뭔가 non static이라고 해야할 거 같지만 생활코딩 그대로 가져옴 ㅋ

클래스.메소드

  • static이 붙으면 클래스에서 가져오는 메소드
  • 클래스 내에 Static 키워드로 선언된 변수
  • 코드가 실행되면 Static 멤버들은 메서드 영역에 저장됨. Static 메서드들은 메서드가 저장된 메모리의 주소가 저장된다.
  • 클래스가 여러 번 생성되어도 Static 변수는 처음 한 번만 생성됨
  • 동일한 클래스 모든 객체들에 의해 공유됨
  • this 키워드 사용 불가

인스턴스.메소드

  • 인스턴스에서 가져오는 메소드의 경우 static을 빼줘야함!
  • 메모리에 올라가지 않음
  • Non-Static
  • 클래스 내에 선언된 변수
  • 객체 생성 시마다 새로운 변수 생성
  • 클래스 변수와 달리 공유되지 않음

예시 코드

class Print{
    public String delimeter;
    public void a(){
        System.out.println(this.delimeter);
        System.out.println("a");
        System.out.println("a");
    }
    public void b(){
        System.out.println(this.delimeter);
        System.out.println("b");
        System.out.println("b");
    }

public static void c(){
    System.out.println("=");
    System.out.println("c");
    System.out.println("c");
}
}
public class staticMethod {

    public static void main(String[] args){
//        Print.a("-");
//        Print.b("-");
        // t1은 Print 클래스를 복사한 인스턴스
        Print t1 = new Print();
        t1.delimeter = "-";

//        Print.a("*");
//        Print.b("*");
        t1.a();
        t1.b();
        // a()는 클래스 소속이 아닌 인스턴스 소속이기 때문에 동작하지 않음
        // Print.a();
        Print.c();
    }

}

출처: 생활코딩 JAVA method

profile
매일매일 조금씩 모여 숲이 되자🐣

2개의 댓글

comment-user-thumbnail
2022년 12월 22일

Static을 할당하게 되면 모든 객체가 메모리를 공유하게 됩니다..

1개의 답글