[Java] static 키워드

·2024년 4월 8일
0

static

staic은 객체가 아니라, 클래스 단위로 가지는 변수를 선언할 때 사용한다.

즉, 객체를 생성하지 않아도 이미 메모리에 올라와있는 변수이다!

=> 해당 클래스로 생성된 객체가 공유할 수 있는 값으로, 이를 이용하면 메모리 절약이 가능하다.

class Employee{

    //인스턴스 변수
    String name;
    static String company="it";
    Employee(String name){
        this.name =name;
    }
    

}

public class Ex03Static {
    public static void main(String[] args) {
        Employee emp1 = new Employee("emp1");
        System.out.println(emp1.name);
        System.out.println(emp1.company); //오류
        //emp1라는 객체가 아니라, Employee라는 클래스가 가지는 값이므로
        //Employee.company로 접근해야함

    }
}

static final?

주로 상수를 할당할 때 사용되는 키워드인데,
클래스가 공유하되, 절대로 변경할 수 없는 값을 할당할 때 사용된다.
(아무나 접근할 수 잆지만, 아무나 변경할 수 없을 때)

package step02.object;


class Employee{

    //인스턴스 변수
    String name;
    static final double PI=3.14;
    //static final 타입 CONSTANT_VALUE
    static String company="it";
    Employee(String name){
        this.name =name;
    }


}

public class Ex03Static {
    public static void main(String[] args) {
        Employee emp1 = new Employee("emp1");
        System.out.println(emp1.name);
        System.out.println(Employee.company);
        Employee.PI=3.15 //오류
        System.out.println(Employee.PI);//접근은 가능

    }
}

단, 메서드를 통해 static에 접근 시, 해당 메서드도 static이어야 함

package step02.object;


class Employee{

    //인스턴스 변수
    String name;
    static String company="it";
    Employee(String name){
        this.name =name;
    }

    String getName(){
        return name;
    }

    String getCompany(){
        return company;
    } //static String getCompany()로 해야함!

}

public class Ex03Static {
    public static void main(String[] args) {
        Employee emp1 = new Employee("emp1");
        System.out.println(emp1.name);
        System.out.println(Employee.company);
        
        emp1.getCompany(); // 오류

    }
}

무작정 static을 쓰는게 좋을까?

모든 객체가 공유하는 값이라면 모르는데, 일부 객체가 가지고 있는 값이라면..
굳이 모든 객체가 사용하지 않는 static을 이용할 필요가 없다.

즉, 무작정 static을 이용해 값을 할당하는 것 보다는, 충분한 설계 후 static을 적용해보는게 좋다.

profile
풀스택 호소인

0개의 댓글