Java - 3. static

Mingi Shin·2023년 10월 5일
0

java

목록 보기
3/10
post-thumbnail

자바에서 static 수정자를 사용함으로써 static 메서드와 변수를 선언할 수 있다.
static 메서드와 변수는 종종 class 메서드와 변수로 불리는데 이는 객체(인스턴스)의 소속이 아닌 class 소속의 메서드와 변수이기 때문이다.

static 멤버들이 선언이 되면 클래스가 처음 참조될 때 메모리에 오직 1개로만 존재하게 된다. 클래스에 대한 모든 객체들은 static 멤버들을 공유하여 사용한다. 공유되어 사용되기 때문에 어떤 한 객체가 static 변수의 값을 변경했다면 다른 모든 객체에 적용된다.

static variables

public class StaticVariables {

  static int id, height;

  void getdata(int a, int b) {
    id=a;
    height=b;
  }
  
  public static void main(String[] args) {
    StaticVariables obj= new StaticVariables();
    obj.getdata(2019, 76);
    System.out.println(id);
    System.out.println(height);
  }
} 

id, height가 static 변수로 class 내에 공유되고 있기 때문에 main에서 static 변수를 호출하기 위해 간단하게 변수명만 적어도 호출이 가능하다.

static methods

public class Helper {

  public static int cube (int num) {
    return num * num * num;
  }
}

Helper 클래스의 cube() 메서드가 static으로 선언되어 있다.

value = Helper.cube(4);

따라서 cube()를 호출하기 위해서는 클래스명에 dot을 붙여 호출한다. (static 메서드는 클래스 참조 시에 메모리에 오직 1개만 적재되고 공유하여 쓰는 class 메서드)

public class StaticVariables {

  static int square(int x) {
    return x*x;
  }
  
  public static void main(String[] args) {
    int result= StaticVariables.square(10);
    System.out.println(result);
  }
}

static 메서드를 호출하기 위해 인스턴스를 생성하는 것이 아닌 class name으로 square()를 호출한다.

static class members

main 메서드는 static으로 선언을 한다. main 메서드가 객체를 생성하지 않고 Java interpreter에 의해 호출되기 때문이다.

instance 변수는 객체가 존재해야 존재하기 때문에 static 메서드는 instance 변수를 참조할 수 없다. static 메서드는 메서드 내부의 지역 변수와 static 변수를 참조한다.

public class StaticVariables {

  static int id, height;
  
  static void getData(int a, int b) {
    id=a;
    height=b;
  }
  
  public static void main(String[] args) {
    StaticVariables.getData(2019, 76);
    System.out.println(id);
    System.out.println(height);
  }
}

static 메서드인 main 메서드는 static 변수인 id, height와 static 메서드 getData()를 참조할 수 있다.

class ComStudent {

  static int id, height;
  
  static void getdata(int a, int b) {
    id=a;
    height=b;
  }
}

public class StaticOutsideClass {

  public static void main(String[] args) {
    ComStudent.getdata(2018, 100);
    System.out.println(ComStudent.id);
    System.out.println(ComStudent.height);
  }
}

ComStudent 클래스의 static 변수와 메서드를 참조하기 위해 main 메서드에서 ComStudent 이름으로 변수와 메서드에 access하고 있다.

profile
@abcganada123 / git:ABCganada

0개의 댓글

관련 채용 정보