Properties / Fields / Attributes

From CSSEMediaWiki
Revision as of 00:41, 13 October 2010 by Filip Kujikis (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Properties represent information about an object, typically associated with its state. They are also often referred to as attributes and are closely related to fields.

Fields

Fields are the lowest level representation of an object's state - they are the instance variables or data of a class. For example:

class Circle
{
     int radius;      // field, data
}

Properties

Properties represent information about object state in a more abstract manner, and resemble methods. Typically they provide an indirect way of accessing fields, but may also provide information that is not stored in a field but results due to an operation on field data.

Examples

In some languages like Java, properties are implemented as ordinary methods, conventionally named as Getters and setters. For example:

class Circle
{
     // field, data
     private int radius;      
    
     // Getter for radius property
     public int getRadius()
     {
         return this.radius;
     }
     // Setter for radius property - 
     public void setRadius(int newValue)
     {
         this.radius = newValue;
     }
     // This is an example of a property that represents information not directly stored by a field.
     public void getDiameter()
     {
         return this.radius * 2;
     }
}

Other languages, like C# for example, provide a special syntax for declaring properties. The C# equivalent of the Java example above is given below.

class Circle
{
     // field, data
     private int radius; 
     // Radius property
     public int Radius
     {
         get
         {
             return this.radius;
         }
         set
         {
             this.radius = value;
         }
     } 
     // Diameter property
     public int Diameter
     {
         get
         {
             return this.radius * 2;
         }
     }
}
Personal tools