JAVA 객체 지향 핵심

(JAVA)static 키워드에 이해 - 9

mynote6676 2025. 4. 17. 14:57

static 변수는 프로그래밍에서 중요한 개념 중 하나입니다. 클래스 변수라고도 불리며, 클래스의 모든 인스턴스가 공유하는 변수입니다. 즉, 객체가 동일한 static 변수의 값을 공유합니다.

 

 

 

 

공통으로 사용하는 변수가 필요한 경우

● 여러 인스턴스가 공유하는 기준 값이 필요한 경우

● 학생마다 새로운 학번 생성

● 카드회사에서 카드를 새로 발급할때마다 새로운 카드 번호를 부여

● 회사에 사원이 입사할때 마다 새로운 사번이 필요한 경우

● 은행에서 대기표를 뽑을 경우(2대 이상)

 

package com._static;

public class NumberPrinter {

    /**
     *  static 변수는, static 메서드는 객체 생성 없이 클래스 이름으로 바로 접근 가능 하다.
     *  왜? heap 메모리에 들어가기 위해서는 new 키워드와 생성자를 호출한 뒤
     *  동작할 수 있지만 method area 영역은 프로그램을 실행 시키면
     *  바로 메모리를 할당 받아 실행되는 영역이기 때문이다.
     */

    private int id;
    // 멤버 변수 (NumberPrinter 소속된 변수)
    // public int waitNumber;

    // waitNumber <-- 멤버 변수가 아니라 class area 영역에 포함된다.
    public static int waitNumber; // static 변수 선언(클래스 변수)

    public NumberPrinter(int id) {
        this.id = id;
        this.waitNumber = 1;
    }

    // 번호표를 출력합니다.
    public void printWaitNumber() {
        System.out.println(id + " 기기에 대기 순번은 : " + waitNumber);
        waitNumber++;
    }

}

 

 

 

 

package com._static;

public class Employee {

    private int employeeId;
    private String name;//이름
    private String department;//부서
    //private int employeeId;
    //private String department;
    //private String name

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

    //getter
    public int getEmployeeId(){
        return employeeId;
        //public int getE
    }
    public String getName(){
        return name;
    }
    public String getDepartment(){
        return department;
    }

}

 

package com._static;

public class Company {

    //static변수는 class변수라고도 한다
    static int emSerialNumber = 1;

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

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

        System.out.println("야스오 :" + employee1.getEmployeeId());
        System.out.println("티모 :" + employee2.getEmployeeId());
        System.out.println("샤코 :" + employee3.getEmployeeId());
        System.out.println("길동 :" + employee4.getEmployeeId());

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

 

package com._static;

public class Card2 {

    //static 변수 : 모든 card 객체가 공유하며, 고유 번호를 생성하기 위해 사용할 수 있다.
    private static int cardCounter = 0;
    //private static inr cardCounter = 0;

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

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

     //static 메서드
    public static int getCardCounter(){
        // static 메서드 나에서 인스턴스 변수를 사용할 수 없다.
        //왜? 인스턴스 변수는 객체가 생성된 이후에 사용될 수 있다.
        //System.out.println("cardName : " + cardName);
        //static변수
        return cardCounter;
        //public static int getCardCounter(){
        //return cardCounter;}
    }

    //인스턴스 메서드를 만들어 보자
    public void showInfo(){
        System.out.println(cardCounter);
        System.out.println(cardName + " 에 고유 번호는 " + cardId + "입니다");
        //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);
        //인스턴스 메서드는 일까 스태이틱 메서드 이다
        //그래서 객체 생성전에 호출해 볼 수있다.
        System.out.println(Card2.getCardCounter());

        //Card2 c1 = new Card2("우리 카드1");
        //System.out.println(c1.cardId);

        //public static void main(String[] args){
        //System.out.println(Card2.getCardCounter());


    }//end of main
}