JAVA

자바 static 변수 및 static 메서드

아이티프로 2023. 1. 24.
반응형

Static(정적) 변수와 static 메소드는 클래스변수로  Class를 인스턴스하지 않아도 참조할 수 있다.
메모리의 데이터영역에 저장하여 인스턴스를 생성하지 않아도 변수값을 공유할 수 있는 장점이 있다.

Static은 상수나 싱글톤을 구현할 때 주로 사용된다.

 

static 변수 와 메서드

 

package javaStudy;

class PiClass {
	public static final double PI = 3.1415;	//final을 사용하여 변경되지 않는 상수값을 지정
}

public class MainClass {
	public static void main(String[] args) {
		System.out.println("원주율 : " + PiClass.PI); //클래스를 인스턴스 생성없이 참조
	}
}

 

싱글톤 예제

 

package javaStudy;
class Singleton {
    private static Singleton one;
    private Singleton() {
    }

    public static Singleton getInstance() {
        if(one==null) {
            one = new Singleton();
        }
        return one;
    }
}

public class SingletonTest {
    public static void main(String[] args) {
        Singleton singleton1 = Singleton.getInstance();
        Singleton singleton2 = Singleton.getInstance();
        System.out.println(singleton1 == singleton2);
    }
}

 

반응형

'JAVA' 카테고리의 다른 글

자바 조건문 if switch  (0) 2023.01.24
자바 반복문 for do while  (0) 2023.01.24
자바 String 클래스  (0) 2023.01.24
자바 생성자  (0) 2023.01.24
자바 오버로딩  (0) 2023.01.24

댓글