The Properties of a Class |
|
In C++ and Java, when creating the member variables of a class, programmers usually "hide" these members in private sections (C++) or create them as private (Java). This technique makes sure that a member variable is not accessible outside of the class so that the clients of the class cannot directly influence the value of the member variable. If you create a member variable as private but still want other classes to access or get the value of such a field, you must then create one or two "accessories", like a door in which the external classes must pass through to access the field. |
A property is a member of a class that plays an intermediary role to a field of the class. For example, if you have a field of class and that member represents the salary of an employee, a property can be the "door" that other classes that need the salary must present their requests to. As such, these external classes cannot just change the salary or retrieve it as they wish. A property can be used to validate their request, to reject or to accept them. A property is used to "filter" access to a field of a class. Therefore, you start by declaring a (private (if you don't make it private, you may be deceiving the purpose of creating a property)) field. Here is an example: using System; namespace Example { public class Square { private double _side; } public class Exercise { static void Main() { } } } Obviously this private field cannot be accessed by an outside class. To let the outside classes access this variable, you would/can create a property. To indicate that you are creating a property, there is a syntax you must follow. To start, you must create a member whose formula resembles a method without the parentheses. Therefore, you would start a property as follows: using System; namespace Example { public class Square { private double _side; // This is a new property public double Side { } } } With regards to their role, there are two types of properties.
|
|
||
Home | Copyright © 2006-2007 FunctionX, Inc. | Next |
|