คำว่า protected เป็น ?member access modifier อีกรูปแบบหนึ่ง ซึ่ง protected จะอนุญาตให้เฉพาะ object ที่สืบทอดมาเท่านั้นที่เข้าถึงและใช้งานได้ ซึ่งจากลักษณะการใช้งานดังกล่าวนั้นเป็นผลดีสำหรับการเขียนโปรแกรมแบบ OOP นั้นเองซึ่งเป็นการบังคับว่าจะต้องสืบทอดจาก class แม่เท่านั้นจะมีสิทธิเข้าถึงและใช้งานได้ เรามาดูตัวอย่างโปรแกรม C# กันดีกว่า เริ่มแรกให้สร้าง Console Application แล้วตั้งชื่อว่า protected
จากนั้นแก้ไขไฟล์ Program.cs ตามนี้
[sourcecode language=”c#”]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace @protected
{
class A
{
protected int x = 123;
}
class B:A
{
public void ShowText()
{
B b = new B();
A a = new A();
//a.x = 66;
b.x = 55;
Console.WriteLine(b.x);
}
}
class Program
{
static void Main(string[] args)
{
B objectB = new B();
objectB.ShowText();
Console.ReadLine();
}
}
}
[/sourcecode]
ผลลัพธ์การรันโปรแกรมจะเห็นว่า Object Class B ซึ่งสืบทอดมาจาก Class A สามารถเรียกใช้งานได้แต่ถ้าลองเอา comment //a.x = 66; โปรแกรมจะ error ซึ่ง Object Class A เองยังไม่สามารถเข้าถึงตัวแปร x ได้เพราะฉะนั้น protected นั้นมีไว้สำหรับ Class ที่สืบทอดเท่านั้น