Chỉ functions cùng class mới truy cập private member. Private giấu member variables/functions khỏi functions/objects khác.
Ví dụ
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();
}
}
}
Kết quả
Length: 10 Width: 14 Area: 140
Biến length, width private nên chỉ method cùng class Rectangle truy cập được.