The protected access specifier hides its member variables and functions
from other classes and objects. This type of variable or function can
only be accessed in child class. It becomes very important while
implementing inheritance.
Example:
Output:
'Protected_Specifier.access.name' is inaccessible due to its protection level.
This is because; the protected member can only be accessed within its child class. You can use protected access specifiers as follow:
Example:
Output
Enter your name: Aav Kumar
My name is Aav Kumar
Example:
using System;
namespace Protected_Specifier
{
class access
{
// String Variable declared as protected
protected string name;
public void print()
{
Console.WriteLine("\nMy name is " + name);
}
}
class Program
{
static void Main(string[] args)
{
access ac = new access();
Console.Write("Enter your name:\t");
// raise error because of its protection level
ac.name = Console.ReadLine();
ac.print();
Console.ReadLine();
}
}
}
namespace Protected_Specifier
{
class access
{
// String Variable declared as protected
protected string name;
public void print()
{
Console.WriteLine("\nMy name is " + name);
}
}
class Program
{
static void Main(string[] args)
{
access ac = new access();
Console.Write("Enter your name:\t");
// raise error because of its protection level
ac.name = Console.ReadLine();
ac.print();
Console.ReadLine();
}
}
}
Output:
'Protected_Specifier.access.name' is inaccessible due to its protection level.
This is because; the protected member can only be accessed within its child class. You can use protected access specifiers as follow:
Example:
using System;
namespace Protected_Specifier
{
class access
{
// String Variable declared as protected
protected string name;
public void print()
{
Console.WriteLine("\nMy name is " + name);
}
}
class Program : access // Inherit access class
{
static void Main(string[] args)
{
Program p=new Program();
Console.Write("Enter your name:\t");
p.name = Console.ReadLine(); // No Error!!
p.print();
Console.ReadLine();
}
}
}
namespace Protected_Specifier
{
class access
{
// String Variable declared as protected
protected string name;
public void print()
{
Console.WriteLine("\nMy name is " + name);
}
}
class Program : access // Inherit access class
{
static void Main(string[] args)
{
Program p=new Program();
Console.Write("Enter your name:\t");
p.name = Console.ReadLine(); // No Error!!
p.print();
Console.ReadLine();
}
}
}
Output
Enter your name: Aav Kumar
My name is Aav Kumar
Comments
Post a Comment