본문 바로가기

자바/객체지향

static 키워드

예제1)


public class Test3 {

public static void main(String[] args) {

System.out.println("main:"+Ex3.x);

System.out.println("main:"+Ex3.y);

//System.out.println("main:"+Ex3.z); //에러.

//static 변수가 아닌 경우 반드시 객체 생성후에만 가능

Ex3.print();

     //Ex3.write(); //에러

Ex3 ob = new Ex3();

ob.write();

}

}


// static 키워드가 붙은 변수나 메소드는 클래스가 메모리에 로딩됨과 동시에 메모리에 할당되므로 객체를 생성하지 않아도 클래스의 이름으로 바로 접근 가능(Ex3.x)

// 클래스 앞에 static 키워드는 내부클래스인 경우만 가능하다.

class Ex3 {

public static int x=10; //static이 들어가서 클래스 변수

public static int y;

static {       // static 초기화 블럭

y=20;

}

int z=30;               //인스턴스변수(필드). 메인메서드에서 사용하려면 객체생성을 해야만 사용가능.

public static void print() { //static이 들어가서 클래스 메소드 => 클래스변수만 사용가능 => 인스턴스변수를 사용하려면 객체생성해야한다.

System.out.println("x;"+x+",y:"+y);

//System.out.println(z); //에러.

// 인스턴스변수, 인스턴스 메소드 접근 불가

// this, super 키워드 사용불가

// 클래스 메소드를 override 할 수 없다.

Ex3 oo=new Ex3();

oo.write();  //객체 생성하여 클래스 메소드 안에서 인스턴스 메소드 사용가능.

}

public void write() { // 인스턴스 메소드

System.out.println("x;"+x+",y:"+y+",z:"+z);

}

}


//static 들어간 변수나 메서드는 다음과 같이 사용 => 클래스이름.변수이름(메서드이름)

//static이 들어간 메서드는 클래스 변수만 사용가능 => 인스턴스 변수를 사용하려면 객체생성.


예제1 결과)


main:10

main:20

x;10,y:20

x;10,y:20,z:30

x;10,y:20,z:30


================================================================================================================================

예제2)

package com.test0520;

public class Test4 {
public static void main(String[] args) {
// Ex4 ob=new Ex4(); // 에러. 생성자가 private 이므로.
Ex4 ob1=Ex4.getInstance();
Ex4 ob2=Ex4.getInstance();
if(ob1==ob2)
System.out.println("동일 객체.....");
ob1.write();
/*
* singleton 패턴
* 객체를 하나만 생성하는 디자인 패턴중 일종
*/
}
}

class Ex4{
private static Ex4 oo; // 아직 선언만한 상태?
private Ex4(){ // 상속할 수도 없다. 객체를 오로지 하나만 만들기 위한 private
}
public static Ex4 getInstance(){
if(oo==null)
oo=new Ex4();
return oo;
}
public void write(){
System.out.println("singleton 예제.....");
}
}

예제2 결과)

동일 객체.....
singleton 예제.....

'자바 > 객체지향' 카테고리의 다른 글

final 키워드  (0) 2013.05.21
업캐스팅 다운캐스팅  (0) 2013.05.19
재정의(override), 중복정의(overloading)  (0) 2013.05.19
자바의 상속  (0) 2013.05.19
Method 메서드  (0) 2013.05.14