클래스 외부에서 멤버 접근하기

접근 제한자는 오직 클래스 외부 코드에 제약을 적용하며, 클래스 내부에서는 접근 분리 규칙이 적용되지 않습니다.

앞서 배웠듯 클래스 내부에서는 모든 멤버에 자유롭게 접근할 수 있습니다.

이제 클래스 외부에서 멤버에 접근하는 방식을 살펴보겠습니다.

클래스 밖에서 public 인스턴스 멤버에 접근하려면 반드시 객체변수명.멤버이름 형식의 점 구문을 사용해야 합니다.

class Program
{
    static void Main(string[] args)
    {
        Worker worker = new Worker(); //객체 생성
        int hours = worker.GetHours(); //객체로 public 함수 호출
        worker.hours = 12; //객체로 public 변수에 값 할당
        Console.WriteLine(worker.hours); //일반 변수처럼 직접 읽기
    }
}

class Worker
{
    int age;
    private double savings;
    public int hours;

    void ReadSavings()
    {
        Console.WriteLine(savings);
    }

    public int GetHours()
    {
        return hours;
    }
}Code language: C# (cs)

Worker의 GetHours 메서드는 public으로 선언되었으므로 외부에서 읽고 수정할 수 있습니다.

Program 클래스의 Main 메서드에서 Worker 객체 worker를 생성합니다.

객체 이름 worker를 통해 접근합니다. 객체 이름은 포인터와 유사하며 참조(메모리 주소)를 담고 있고 점(.) 기호와 함께 사용해 공개 멤버에 접근할 수 있습니다.

외부에서 인스턴스 멤버에 접근하는 형식:객체변수.public필드 / public메서드().

private 멤버는 클래스 외부에서 점 구문으로 접근할 수 없습니다.

클래스 밖에서 private 멤버(필드, 함수)에 접근하려고 하면 컴파일 오류가 발생합니다.

오류 예시

class Program
{
    static void Main(string[] args)
    {
        Worker worker = new Worker(); 
        int hours = worker.GetHours(); 
        worker.hours = 12;
        Console.WriteLine(worker.hours);

        worker.ReadSavings();
        worker.age = 20;
        worker.savings = 1000000000.0;
    }
}

class Worker
{
    int age;
    private double savings;
    public int hours;

    void ReadSavings()
    {
        Console.WriteLine(savings);
    }

    public int GetHours()
    {
        return hours;
    }
}Code language: C# (cs)

다른 예시를 살펴보겠습니다

class Rectangle
{
    // public 인스턴스 필드:가로 Length, 세로 Width
    public int Length, Width;

    // 인스턴스 메서드:사각형 넓이 계산 후 반환
    public int GetArea()
    {
        return Length * Width;
    }
}

class Program
{
    static void Main()
    {
        // 독립적인 사각형 인스턴스 두 개 생성
        Rectangle rect1 = new Rectangle();
        Rectangle rect2 = new Rectangle();

        // 각 사각형에 길이 할당, 데이터는 서로 분리됨
        rect1.Length = 10; rect1.Width = 5;
        rect2.Length = 8;  rect2.Width = 7;

        // 값 읽고 메서드 호출해 넓이 출력
        Console.WriteLine("사각형1:가로{0},세로{1},넓이{2}", rect1.Length, rect1.Width, rect1.GetArea());
        Console.WriteLine("사각형2:가로{0},세로{1},넓이{2}", rect2.Length, rect2.Width, rect2.GetArea());
    }
}Code language: C# (cs)

사각형 클래스 예시입니다. Length와 Width 두 개의 공개 필드에 가로 세로 길이를 저장하고 GetArea 함수로 넓이를 계산합니다.

이 멤버들은 모두 공개 상태입니다.

실행 결과

사각형1:가로10,세로5,넓이50
사각형2:가로8,세로7,넓이56

메모리 상 저장 구조는 다음과 같습니다

두 객체는 메모리에 따로 저장되며 각자 Length와 Width 값을 갖고 서로 영향을 주지 않습니다.

클래스 외부에서 멤버 접근하기

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다