Back-End/Java

[Java] 23. static 메서드 - 학번 생성 프로그램 만들기

nanee_ 2021. 9. 7. 00:12
728x90
반응형
SMALL

정적 메서드 (static 메서드)

: static 키워드를 사용해 static data 영역에 있어서 인스턴트들이 공유하는 메서드이다.

 

생성 방법

접근지시제어자 static 데이터형 메서드명(매개변수1, ...){};

 

static 메서드 안에서는 멤버변수를 사용할 수 없다.

왜냐하면, static data 영역은 객체가 생성되기 전에 접근해서 사용할 수 있는 static 이기 때문이다.

객체들이 Heap 메모리에 올려지지 않았으니 그 객체의 멤버변수에 접근할 수 없는 것이다.

 

사용방법

static은 클래스 이름으로 접근이 가능하다. (new 키워드 사용 X)

클래스명.static메서드();

 

객체 생성 전에도 사용가능하다.

 

 

 

학번 생성 예시 코드

public class Student {

  // static 변수
  public static int serialNum = 20211000;

  // 멤버변수
  private int studentId;
  private String name;
  private String major;

  public int getStudentId() {
  	return studentId;
  }

  // 생성자
  public Student(String name, String major) {
    serialNum++;
    this.name = name;
    this.major = major;
    this.studentId = serialNum;
  }

  // static 메서드
  public static int getSerialNum() {
  	return serialNum;
  }

}

 

static 키워드를 사용해 serialNum 변수에 학번의 시작번호로 초기화해주었다.

 

멤버변수로 학번(studentId), 이름(name), 학과(major) 을 선언해 주었고,

private 이기 때문에 getter을 이용해 외부에서 학번 변수에 접근 가능하도록 해 준다.

 

serialNum 을 반환해주는 getSerialNum() static 메서드를 만들어 주었다.

 

public class MainTest {
  public static void main(String[] args) {

    // 객체 생성 전에 접근 가능
    int tempNum = Student.getSerialNum();
    System.out.println(tempNum);

    // 객체 생성
    Student student1 = new Student("김도영","국어국문학과");
    Student student2 = new Student("정재현","영어영문학과");

    System.out.println(student1.getStudentId());
    System.out.println(student2.getStudentId());
  }
}

 

tempNum 변수로 static 변수, 메서드가 객체 생성 전에 접근이 가능하다는 것을 확인할 수 있다.

 

객체를 생성하고, 생성된 객체에서 static 메서드인 getStudentId()를 통해 설정된 학번을 출력시킨다.

 

 

 

 

 

 

 

 

728x90
반응형
LIST