เฉพาะฟังก์ชันในคลาสเดียวกันเท่านั้นที่เข้าถึง private members ได้ Private ซ่อนตัวแปรและฟังก์ชันจากฟังก์ชันและอ็อบเจกต์อื่น
ตัวอย่าง
using System;
namespace RectangleApplication {
class Rectangle {
private double length;
private double width;
public void Acceptdetails() { length = 10; width = 14; }
public double GetArea() { return length * width; }
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.Acceptdetails(); r.Display(); Console.ReadLine();
}
}
}
ผลลัพธ์
Length: 10 Width: 14 Area: 140
ตัวแปร length และ width เป็น private ดังนั้นเมธอดในคลาสเดียวกันเข้าถึงได้