본문 바로가기

Java

static 변수 개념

static 키워드의 이해

클래스 변수 라고도 한다.
클래스의 모든 인스턴스가 공유하는 변수다.
여러 객체들이 동일한 변수를 공유할 필요가 있을 때 사용한다.

 

ex 은행의 변호표

package com.static1;
// 클래스 설계
public class NumberPrinter {
    /*
    static 변수, static 메서드는
    객체 생성 없이도
    클래스 이름으로 바로 접근 가능하다.

    왜?
    Heap 메모리에 들어가기 위해서는
    new 키워드와 생성자를 호출한 뒤 동작하지만

    Method area 영역은
    프로그램을 실행시키면
    바로 메모리를 할당받아 실행되는 영역이다.
     */

    //멤버 변수 - NumberPrinter에 소속된 변수
    private int id;
//    public int waitNumber;
    public static int waitNumber; // static 변수 선언 (클래스 변수)

    // waitNumber 는 멤버변수가 아니라 class area 영역에 소속된다.

    //생성자
    public NumberPrinter(int id) {
        this.id = id;
        waitNumber = 1;
    }

    //번호표 출력 메서드
    public void printWaitNumber() {
        System.out.println(id + "의 대기순번은 " + waitNumber);
        waitNumber++;
    }
    //대기순번이 늘어나야 한다
}//end of class
package com.static1;
    // 번호표 코드 실행측
public class PrinterTest1 {
    //main
    public static void main(String[] args) {

        int a = 10;
//        static int b = 20;
        /*
        static 변수는 태양이다

        순서가 있다.
        프로그램을 실행시키면

        static의 저장영역은 먼저 활성화된다.
         */


        NumberPrinter n1 = new NumberPrinter(1);
        NumberPrinter n2 = new NumberPrinter(2);

        n1.printWaitNumber();
        n2.printWaitNumber();
        n1.printWaitNumber();
        n1.printWaitNumber();
        n2.printWaitNumber();
        n2.printWaitNumber();
    }//end of main
}//end of class


static 변수는
객체 생성 전에 사용 가능

마찬가지로

static 메서드는
객체 생성 전에 사용 가능

Class Area
static 메모리라고도 부른다.

1. 컴파일 시점
2. 런타임 (
static 메모리 영역
stack 영역
heap영역
)

 

package com.static1;
//클래스 설계
public class Employee {

    //속성
    private int employeeId;
    private String name; //
    private String department;

    //생성자
    public Employee(String name) {
        this.name = name;
//        employeeId = 1;
        /*
        클래스 변수를 활용해보자.
        클래스 이름으로 접근할 수 있다.
        Company.empSerialNumber
         */
        employeeId = Company.empSerialNumber;
        Company.empSerialNumber ++;
    }

    //메서드

    //getter
    public int getEmployeeId() {
        return employeeId;
    }
    public String getName() {
        return name;
    }
    public String getDepartment() {
        return department;
    }
}
package com.static1;
public class Company {

    //static 변수는 클래스 변수 라고도 한다.

    static int empSerialNumber = 1;

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

        Employee employee1 = new Employee("야스오");
        Employee employee2 = new Employee("티모");
        Employee employee3 = new Employee("샤코");
        Employee employee4 = new Employee("홍길동");
        Employee employee5 = new Employee("장길산");

        System.out.println("야스오: " + employee1.getEmployeeId());
        System.out.println("티모: " + employee2.getEmployeeId());
        System.out.println("샤코: " + employee3.getEmployeeId());
        System.out.println("홍길동: " + employee4.getEmployeeId());
        System.out.println("장길산: " + employee5.getEmployeeId());
    }//end of main
}//end of class

static 변수를 이용해 고유번호를 순서대로 할당했다.

 

static 변수를 활용한 고유번호 생성예제

package com.static1;
//Card 클래스 설계
    //신용카드를 설계해보자
public class Card {

    //멤버변수
    private String name;
    private int cardId;

    static int cardIdNumber =1;

    //생성자
    public Card(String name) {
        this.name = name;
        this.cardId = cardIdNumber;
        cardIdNumber ++;
    }

    //메서드

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

        Card card1 = new Card("첫카드");
        Card card2 = new Card("둘카드");
        Card card3 = new Card("셋카드");
        Card card4 = new Card("넷카드");

        System.out.println("첫카드 ID: " + card1.cardId);
        System.out.println("둘카드 ID: " + card2.cardId);
        System.out.println("셋카드 ID: " + card3.cardId);
        System.out.println("넷카드 ID: " + card4.cardId);

    }//end of main
}//end of class

 

static 변수와 static 함수는 객체 선언 없이도 쓸 수 있다.

package com.static1;
    //클래스 설계
public class Card2 {
    /*
    static 변수
    모든 Card 객체가 공유한다.
    고유번호를 생성하는 데 활용된다.
     */
    private static int cardCounter = 0;

    //인스턴스 변수
    private final int cardId;
    private final String cardName;

    //생성자
    public Card2(String cardName) {
        this.cardName = cardName;
        this.cardId = ++cardCounter;
    }

    //static 메서드 - 함수
    public static int getTotalCards() {

//        System.out.println("cardName" + cardName);
        /*
        static 메서드 안에서 인스턴스 변수를 사용할 수 없다.
        인스턴스 변수는 객체가 생성된 이후에 사용할 수 있다.
         */

        //static 변수
        return cardCounter;
    }

    //인스턴스 메서드
    public void showInfo() {
        System.out.println(cardCounter);
        System.out.println(cardName + " 의 고유번호는 " + cardId);
        //인스턴스 메서드에선 인스턴스 변수 사용 가능
    }

    //메인
    public static void main(String[] args) {
        /*
        static 변수는
        객체 생성 전에 사용 가능

        마찬가지로

        static 메서드는
        객체 생성 전에 사용 가능

        사용법은
        클래스 이름으로 접근 가능
         */
        System.out.println(Card2.cardCounter); // static 변수

        System.out.println(Card2.getTotalCards()); // static 메서드

//        Card2 card1 = new Card2("우리카드1"); // 객체 생성
//        Card2 card2 = new Card2("우리카드2");
//
//        System.out.println(card1.cardName + " 고유번호는 " + card1.cardId);
//        System.out.println(card2.cardName + " 고유번호는 " + card2.cardId);

    }//end of main
}//end of class
package com.static1;
    //클래스 설계
public class Card2 {
    /*
    static 변수
    모든 Card 객체가 공유한다.
    고유번호를 생성하는 데 활용된다.
     */
    private static int cardCounter = 0;

    //인스턴스 변수
    private final int cardId;
    private final String cardName;

    //생성자
    public Card2(String cardName) {
        this.cardName = cardName;
        this.cardId = ++cardCounter;
    }

    //static 메서드 - 함수
    public static int getTotalCards() {

//        System.out.println("cardName" + cardName);
        /*
        static 메서드 안에서 인스턴스 변수를 사용할 수 없다.
        인스턴스 변수는 객체가 생성된 이후에 사용할 수 있다.
         */

        //static 변수
        return cardCounter;
    }

    //인스턴스 메서드
    public void showInfo() {
        System.out.println(cardCounter);
        System.out.println(cardName + " 의 고유번호는 " + cardId);
        //인스턴스 메서드에선 인스턴스 변수 사용 가능
    }

    //메인
    public static void main(String[] args) {
        /*
        static 변수는
        객체 생성 전에 사용 가능

        마찬가지로

        static 메서드는
        객체 생성 전에 사용 가능

        사용법은
        클래스 이름으로 접근 가능
         */
        System.out.println(Card2.cardCounter); // static 변수

        System.out.println(Card2.getTotalCards()); // static 메서드

//        Card2 card1 = new Card2("우리카드1"); // 객체 생성
//        Card2 card2 = new Card2("우리카드2");
//
//        System.out.println(card1.cardName + " 고유번호는 " + card1.cardId);
//        System.out.println(card2.cardName + " 고유번호는 " + card2.cardId);

    }//end of main
}//end of class