본문으로 바로가기

클래스 내부에는 클래스 변수 인스턴스 변수 2가지로 나뉜다. 각각의 특징에 대해 알아보도록 하자.

 

1. 클래스 변수

 

클래스 변수는 클래스 내에서 static 붙여서 선언한 변수를 의미한다. static 붙였기 때문에 정적변수(Static variable)이라고도 한다.

클래스 변수의 특징은 클래스가 여러 인스턴스로 선언되어도 동일한 값을 가져온다는 점이다.

 

아래 예제코드를 통해 자세히 알아보자.

 

exstaticVar.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package exVariable;
 
public class exstaticVar {
 
    public static String testVar = "test";
 
    public static void main(String[] args) {
        exstaticVar test1 = new exstaticVar();
        exstaticVar test2 = new exstaticVar();
        
        System.out.println(test1.testVar);
        
        test2.testVar = "change test";
        
        System.out.println(test1.testVar);
    }
}
 
 

 

결과

	test
	change test

 

클래스 객체 test1 test2 각각 생성하였다. 

 

  1. test1.testVar 출력함으로써 첫번째 결과인 test값이 화면에 출력됨을 확인하였다.

  2. 그이후 test2.testVar = "change test"; 통해 test2객체에서 testVar변수에 접근하여 값을 변경하였다.

  3. 그리고는 test1.testVar 출력하였더니 값이 change test 변함을 확인할 있다.

 

결과와 같이 서로다른 어느 객체에서 static변수에 접근하여 값을 바꾼다면 생성된 모든 객체 내부의 static변수는 값이 동일하게 바뀐다.

쉽게 설명하자면 static변수는 생성된 모든 객체에서 공유한다고 생각하면 된다.

 

클래스변수는 어떻게 사용할 있을까??. 객체가 여러 생성되어도 특정 데이터는 모든 객체에서 공유하여 사용하여야 활용한다.

 

아래 소스를 보자.

 

student.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package exVariable;
 
public class student {
    public static int regStudentNum=0;
 
    public static void main(String[] args) {
        student 영수 = new student();
        student 민수 = new student();
        
        영수.regStudentNum++;
        민수.regStudentNum++;
        
        System.out.println(영수.regStudentNum);
    }
}
 
 

 

결과

	2

 

소스는 학생 객체가 생길때 마다 등록된 학생수를 늘리는 예제 코드이다.

영수객체와 민수객체가 각기 생성되고, 개체에서 변수값을 늘려주면 서로 공유되어 있는 값이기 때문에 2라는 결과를 확인 있다.

 

 

2. 인스턴스 변수

 

클래스 변수의 반대로 생각하면 이해하기 쉽다. 객체가 생성되면 해당 객체에 종속되기 때문에 개체별로 별도의 가진다. student클래스에서 static 제거하고 출력을 해보자.

 

student.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package exVariable;
 
public class student {
    public int regStudentNum=0;
 
    public static void main(String[] args) {
        student 영수 = new student();
        student 민수 = new student();
        
        영수.regStudentNum++;
        민수.regStudentNum++;
        
        System.out.println(영수.regStudentNum);
    }
}
 
 

 

결과

	1

 

static이었으면 값을 공유하기 때문에 2라는 결과를 기대했겠지만, 인스턴스 변수는 각각 객체에 값이 할당되기 때문에 1이라는 결과가 출력됨을 있다.

인스턴스 변수는 객체별로 고유한 값을 지정해야 할때 사용한다. student클래스를 아래와 같이 변경하여 보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package exVariable;
 
public class student {
    public static int regStudentNum=0;     // 등록된 학생수는 객체수가 증가할때마다 늘려야 하기 때문에 static변수로 선언
    public String name;                 // 학생은 각기 고유한 이름을 가지고 있어야 하기 때문에 인스턴스 변수로 선언
 
    public static void main(String[] args) {
        student 영수 = new student();
        student 민수 = new student();
        
        //영수 객체 선언 후 등록 인원 +1, 이름 지정
        영수.regStudentNum++;
        영수.name = "박영수";
        
        //민수 객체 선언 후 등록 인원+1, 이름 지정
        민수.regStudentNum++;
        민수.name = "최민수";
        
        System.out.println(영수.regStudentNum);
        System.out.println(영수.name);
 
        System.out.println(민수.regStudentNum);
        System.out.println(민수.name);
    }
}
 
 

 

결과

    2
    박영수

    2
    최민수

 

 

학생이 등록되면 등록된 인원만큼 학생수를 늘려야 하기 때문에 regStudentNum static 붙여 클래스 변수로 선언하였다.

하지만 각각의 학생은 고유한 이름을 가지고 있어야 하므로 name 인스턴스 변수로 두어 객체마다 값을 가지도록 셋팅하였다.

 

 

 

3. static method(정적 메소드)

 

정적메소드는 메소드에 static 붙이면 된다. 기본 골격은 다음과 같다.

 

접근제어 static 반환타입 메소드명(파라미터…)

 

정적메소드는 인스턴스 변수를 사용할 없으며 static으로 선언된 변수만 사용가능하다. 또한 사용하는 곳에서 따로 객체 생성없이 클래스명.메소드명 으로 호출이 가능하다. 그렇다면 정적 메소드는 어디서 사용할까? 특정한 기능을 담당하는 util 기능에서 많이 사용한다

 

calculator.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package exVariable;
 
public class calculator {
 
    public static int sum(int a, int b) {
        return (a + b);
    }
    
    public static int multi(int a, int b) {
        return (a * b);
    }
    
    public static int divide(int a, int b) {
        return (a / b);
    }
    public static void main(String[] args) {
        
        //static 메소드는 객체 생성없이 클래스명.메소드명으로 호출이 가능하다.!!!
        System.out.println(calculator.sum(35));
        System.out.println(calculator.multi(25));
        System.out.println(calculator.divide(205));
    }
}
 
 

 

소스와 같이 더하기, 곱하기, 나누기와 같이 유용한 util기능은 static메소드로 지정후에 객체 생성없이 클래스.메소드명으로 호출하여 바로바로 사용이 가능하다. 굉장히 많이 쓰는 방식이므로 해당 내용에 대해서 반드시 숙지하도록 하자.