[2021년 정보시스템감리사][소프트웨어공학] 32번
32. 다음은 Java 프로그램의 코드 일부분을 보여준다. 이 프로그램을 컴파일할 때 (가) ~ (라) 라인 중에서 컴파일 오류가 발생하지 않는 부분(라인)들만으로 가장 적절하게 묶인 것은?
public class Test
{
private int a = 0;
private static int count = 0;
public int getA( ) { return a; }
public static int getCount( ) { return count;
}
public static void test( ) {
int sum = 0;
sum = a; // (가)
sum += count; // (나)
System.out.println( getA( ) ); // (다)
System.out.println( getCount( ) ); // (라)
}
}
① 가, 다
② 나, 라
③ 가, 나, 다
④ 가, 나, 다, 라
[해설]
“메모리에 저장되어 있는 데이터만 접근 가능하다.”
▣ static(class) 변수 특징
- 객체(instance)를 생성하지 않고도 Static 자원에 (class 차원에서)접근이 가능
- (메모리에 저장되지 않은) 클래스 멤버 (instance)변수를 대입할 수 없다. (접근 시 컴파일러 에러)
- 객체들이 공유하여 사용한다.
▣ static(class) 함수 특징
- 객체의 생성 없이 호출이 가능
- 함수 내에서 멤버 (instance)변수, 멤버 함수에 접근 불가(접근 시 컴파일러 에러) (가), (다) 상황
- this 키워드 사용 불가(사용자 컴파일러 에러)
class StaticMethod {
int n;
void f1(int x) { n = x; } // 정상
void f2(int x) { n = x; } // 정상
static int m;
static void s1(int x) { n = x; } // 컴파일 오류. static 메서드는 non-static 필드 사용 불가
static void s2(int x) { f1(3); } // 컴파일 오류. static 메서드는 non-static 메서드 사용 불가
static void s3(int x) { m = x; } // 정상. static 메서드는 static 필드 사용 가능
static void s4(int x) { s3(3); } // 정상. static 메서드는 static 메서드 호출 가능
void f1(int x) { this.n = x; } // 정상
void f2(int x) { this.m = x; } // non-static 메서드에서는 static 멤버 접근 가능
static void s1(int x) { this.n = x; } // 컴파일 오류. static 메서드는 this 사용 불가
}
댓글
댓글 쓰기