Access Modifiers

We know that two of the key ideas of OOP are encapsulation and inheritance.

Encapsulations allows us to bind data and actions together and to restrict access to them in order to protect the data within. To determine the levels of access we use access modifiers.

It is important to understand how these modifiers behave when we use them when applying inheritance.

The public modifier (+) permits a member of a class to be accessed from any class.

The private modifier (-) restricts a member of a class so that it can only be accessed by code within its own class but not derived classes.

Create a new project and add the classes below.

class ClassA

{

private string name;


public string Name { get { return name; } }


public ClassA()

{

this.name = "Instance of Class A";

}

}


class ClassB : ClassA

{

public ClassB()

{

this.name = "Instance of Class B";

}

}


class MainClass

{

public static void Main(string[] args)

{

ClassB demoObject = new ClassB();


Console.WriteLine(demoObject.Name);

Console.ReadKey(true);

}

}

You will notice that it will not compile due to an error in the constructor for ClassB.

This is because despite ClassB inheriting from ClassA, it does not have access to the field 'name'.

By changing the access modifier for the field 'name' to protected, the code will now work, and ClassB is able to access the data in the field.

In order to allow derived classes access to private members we need to change the modifier to protected.

The protected modifier (#) restricts a member of a class so that it can only be accessed by code within its own class and any derived classes.

Keywords

Protected

This is an Access Modifier (similar to private) that is used to flag members of the class as 'protected'. This means that that member can be access by the class and any derived classes, but cannot be accessed from outside of the clas.