JAVA

static멤버 , non - static 멤버

yujin0517 2021. 7. 7. 13:22

static 멤버와 non - static 멤버

 

static 멤버  (클래스 멤버, 정적 멤버)

  • 공간적 특성 - static 멤버는 클래스 당 하나만 생성된다. 
  • 시간적 특성 - static 멤버는 클래스가 로딩될 때 공간이 할당된다. 
  • 공유의 특성 - static 멤버는 해당 클래스의 모든 객체에 의해 공유된다. 
public class Main {
    static int a;                    //static 필드
    public static void b() { ... }   //static 메소드
}

- 생성자에는 static을 붙여서 사용할 수 없음. 

- static 멤버의 시간적 특성으로 객체가 생기기 전에 이미 static 멤버는 생성되어있고, 사용이 가능함. 또한, 객체가 사라져도 static 멤버는 사라지지 않고, 프로그램이 종료될 때 사라짐.

 

non - static 멤버 (인스턴스 멤버)

  • 공간적 특성 - non - static 멤버는 객체마다 독립적으로 존재한다.
  • 시간적 특성 - non - static 멤버는 객체 생성 후 사용이 가능하다. 
  • 비공유의 특성 - non - static 멤버는 다른 객체에 의해 공유되지 않는다. 
public class Main {
    int a;
    public void b() { ... } 
}

- non - static 멤버의 시간적 특성으로 객체가 생성될 때 non - static 멤버가 생성되고, 사용 가능함. 또한 객체가 사라지면 non - static 멤버도 사라짐.

 

static의 활용 

non - static 멤버 변수가 static 메소드에 접근하기 위해서는 객체 생성이 필요하고, static 멤버 변수가  static 메소드가 접근하거나 non - static 메소드에 접근할 때는 객체 생성을 하지 않아도 된다. 

- non - static 멤버 변수가 static 메소드에 접근

public class Example {
    public int num;                            //non - static 멤버 변수
    
    public static void main(String[] args) {   //static 메인 메소드
    	Example ex = new Example();            //클래스 객체 생성 
        ex.num = 10;                           //객체에 접근하여 값을 대입
        System.out.println(ex.num);
    }
}

 

- static 멤버 변수가 static 메소드에 접근 

public class Example {
    public static int a;
    public static int b;
    public static int sum;
    
    public static void main(String[] args) {
    	Example.a = 10;
        Example.b = 20;
        Example.sum = a + b;
        System.out.println(Example.sum);
    }
}

 

연습문제 

-> 다음 코드의 오류 수정하기

public class Car {
	int speed;
    void run() {
    	System.out.println("스피드 : " + speed);	
    }
    
    public static void main(String[] args) {
    	speed = 60;
        run();
    }
}

 

방법 1) main 메소드 내부 수정하기

public class Car {
	int speed;
    void run() {
    	System.out.println("스피드 : " + speed);
    }
    
    public static void main (String[] args) {
    	Car car = new Car();   //객체 생성
        car.speed = 60;        //객체에 접근하여 변수에 값을 대입
        car.run();
    }
}

방법 2) main 메소드 외부 수정하기 

public class Car {
	static int speed;     //static 필드
    static void run() {   //static 메소드
    	System.out.println("스피드 : " + speed);
    }
    
    public static void main(String[] args) {
    	speed = 60;
        run();
    }
}

 

다음 글에서는 this 접근자에 대해 설명하겠습니다.

감사합니다!

 

2021.07.07

'JAVA' 카테고리의 다른 글

[자바] 업캐스팅, 다운캐스팅 / instanceof 연산자  (0) 2021.07.08
this 레퍼런스  (0) 2021.07.08
힙/스택 영역 표현 (1)  (0) 2021.07.06
접근지정자 / setter, getter 메소드  (0) 2021.07.05
클래스와 객체생성 및 활용  (0) 2021.07.05