This is very basic and little lengthy way of exposing private field-data through accessor and mutator methods. In this field-data is declared private and then public accessor and mutator methods are formed through which private field-data can be accessed indirectly.
Example:
class Company
{
// field-data declared private
private string nameOfCompany;
private int licenseNumber;
//accessor method to get the value
public string getName()
{
return nameOfCompany;
}
// mutator method to assign the value to private field-data
public void setName(string name)
{
// check condition before assigning value to private field-data
if(name.Length < 26)
{
nameOfCompany = name;
}
else
{
Console.WriteLine("Name exceeds maximum limit");
}
//similarly accessor method for private field-data licenseNumber
public int getLicenseNumber()
{
return licenseNumber;
}
//similarly mutator method to assign the value to private field-data licenseNumber
public void setLicenseNumber( int licenseNum )
{
licenseNumber = licenseNum;
}
}
Note:
if there're too many field-data members in a class then making accessors and mutators for each of those field-data members makes the code too lengthy, therefore it's not preferable to choose this syntax in case number of field-data members is large.
Note:
if there're too many field-data members in a class then making accessors and mutators for each of those field-data members makes the code too lengthy, therefore it's not preferable to choose this syntax in case number of field-data members is large.
No comments:
Post a Comment