공개 액세스 지정자
공용 액세스 지정자를 사용하면 클래스에서 해당 멤버 변수와 멤버 함수를 다른 함수 및 개체에 노출할 수 있습니다. 모든 공개 멤버는 클래스 외부에서 액세스할 수 있습니다.
예시
using System;
namespace Demo {
class Rectangle {
public double length;
public double width;
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
} //end class Rectangle
class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.length = 7;
r.width = 10;
r.Display();
Console.ReadLine();
}
}
} 출력
Length: 7 Width: 10 Area: 70
보호된 액세스 지정자
보호된 액세스 지정자를 사용하면 자식 클래스가 기본 클래스의 멤버 변수와 멤버 함수에 액세스할 수 있습니다.
보호된 멤버에 액세스하는 보호된 액세스 수정자의 예를 살펴보겠습니다.
예시
using System;
namespace MySpecifiers {
class Demo {
protected string name = "Website";
protected void Display(string str) {
Console.WriteLine("Tabs: " + str);
}
}
class Test : Demo {
static void Main(string[] args) {
Test t = new Test();
Console.WriteLine("Details: " + t.name);
t.Display("Product");
t.Display("Services");
t.Display("Tools");
t.Display("Plugins");
}
}
} 출력
Details: Website Tabs: Product Tabs: Services Tabs: Tools Tabs: Plugins
비공개 액세스 지정자
개인 액세스 지정자를 사용하면 클래스가 다른 함수 및 개체에서 해당 구성원 변수 및 구성원 함수를 숨길 수 있습니다. 같은 클래스의 함수만 private 멤버에 액세스할 수 있습니다. 클래스의 인스턴스라도 private 멤버에 액세스할 수 없습니다.
예시
using System;
namespace Demo {
class Rectangle {
//member variables
private double length;
private double width;
public void Acceptdetails() {
length = 10;
width = 15;
}
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
} 출력
Length: 10 Width: 15 Area: 150