Properties / Fields / Attributes
m (Reverted edits by Ebybymic (Talk); changed back to last version by Filip Kujikis) |
|
(One intermediate revision by one user not shown) |
Latest revision as of 03:03, 25 November 2010
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.
Contents |
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; } } }