A property, in some
object-oriented
Object-oriented programming (OOP) is a programming paradigm based on the concept of " objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of p ...
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming ...
s, is a special sort of
class
Class or The Class may refer to:
Common uses not otherwise categorized
* Class (biology), a taxonomic rank
* Class (knowledge representation), a collection of individuals or objects
* Class (philosophy), an analytical concept used differentl ...
member, intermediate in functionality between a
field
Field may refer to:
Expanses of open ground
* Field (agriculture), an area of land used for agricultural purposes
* Airfield, an aerodrome that lacks the infrastructure of an airport
* Battlefield
* Lawn, an area of mowed grass
* Meadow, a grass ...
(or data member) and a
method
Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to:
*Scien ...
. The syntax for reading and writing of properties is like for fields, but property reads and writes are (usually) translated to '
getter
A getter is a deposit of reactive material that is placed inside a vacuum system to complete and maintain the vacuum. When gas molecules strike the getter material, they combine with it chemically or by . Thus the getter removes small amounts of ...
' and '
setter
The setter is a type of gundog used most often for hunting game such as quail, pheasant, and grouse.
In the UK, the four setter breeds, together with the pointers, usually form a subgroup within the gundog group as they share a common fun ...
' method calls. The field-like syntax is easier to read and write than many method calls, yet the interposition of method calls "under the hood" allows for
data validation
In computer science, data validation is the process of ensuring data has undergone data cleansing to ensure they have data quality, that is, that they are both correct and useful. It uses routines, often called "validation rules", "validation cons ...
,
active updating (e.g., of
GUI
The GUI ( "UI" by itself is still usually pronounced . or ), graphical user interface, is a form of user interface that allows users to interact with electronic devices through graphical icons and audio indicator such as primary notation, inste ...
elements), or implementation of what may be called "
read-only fields".
See an instructive example for C# language below.
Support in languages
Programming languages that support properties include
ActionScript 3
ActionScript is an object-oriented programming language originally developed by Macromedia Inc. (later acquired by Adobe). It is influenced by HyperTalk, the scripting language for HyperCard. It is now an implementation of ECMAScript (meaning ...
,
C#,
D,
Delphi
Delphi (; ), in legend previously called Pytho (Πυθώ), in ancient times was a sacred precinct that served as the seat of Pythia, the major oracle who was consulted about important decisions throughout the ancient classical world. The oracle ...
/
Free Pascal
Free Pascal Compiler (FPC) is a compiler for the closely related programming-language dialects Pascal and Object Pascal. It is free software released under the GNU General Public License, witexception clausesthat allow static linking against its ...
,
eC,
F#,
Kotlin,
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
,
Objective-C 2.0,
Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
,
Scala,
Swift
Swift or SWIFT most commonly refers to:
* SWIFT, an international organization facilitating transactions between banks
** SWIFT code
* Swift (programming language)
* Swift (bird), a family of birds
It may also refer to:
Organizations
* SWIFT, ...
,
Lua
Lua or LUA may refer to:
Science and technology
* Lua (programming language)
* Latvia University of Agriculture
* Last universal ancestor, in evolution
Ethnicity and language
* Lua people, of Laos
* Lawa people, of Thailand sometimes referred t ...
, and
Visual Basic Visual Basic is a name for a family of programming languages from Microsoft. It may refer to:
* Visual Basic .NET (now simply referred to as "Visual Basic"), the current version of Visual Basic launched in 2002 which runs on .NET
* Visual Basic (cl ...
.
Some object-oriented languages, such as
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
and
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
, do not support properties, requiring the programmer to define a pair of ''
accessor'' and ''
mutator'' methods instead.
Oberon-2
Oberon-2 is an extension of the original Oberon programming language that adds limited reflection and object-oriented programming facilities, open arrays as pointer base types, read-only field export, and reintroduces the FOR loop from Modula-2. ...
provides an alternative mechanism using object variable visibility flags.
Other languages designed for the
Java Virtual Machine, such as
Groovy
''Groovy'' (or, less commonly, ''groovie'' or ''groovey'') is a slang colloquialism popular during the 1950s, '60s and '70s. It is roughly synonymous with words such as "excellent", "fashionable", or "amazing", depending on context.
History
The ...
, natively support properties.
While
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
does not have first class properties, they can be emulated with
operator overloading
In computer programming, operator overloading, sometimes termed ''operator ad hoc polymorphism'', is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading i ...
.
Also note that some C++ compilers support first class properties as language extensions.
* In
Microsoft Visual Studio
Visual Studio is an integrated development environment (IDE) from Microsoft. It is used to develop computer programs including websites, web apps, web services and mobile apps. Visual Studio uses Microsoft software development platforms such a ...
,
GCC, and
llvm/clang, the
__declspec(property)
creates properties similar to
C#.
*
Borland C++
Borland C++ is a C and C++ IDE (integrated development environment) for MS-DOS and Microsoft Windows. It was the successor to Turbo C++ and included a better debugger, the Turbo Debugger, which was written in protected mode DOS.
Libraries
O ...
and
Borland/CodeGear/Embarcadero C++Builder use the
__property
keyword.
In many object oriented languages properties are implemented as a pair of accessor/mutator methods, but accessed using the same syntax as for public fields. Omitting a method from the pair yields a ''read-only'' or an uncommon ''write-only'' property.
In some languages with no built-in support for properties, a similar construct can be implemented as a single method that either returns or changes the underlying data, depending on the context of its invocation. Such techniques are used e.g. in
Perl
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
.
Some languages (
Ruby
A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
,
Smalltalk
Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Ka ...
) achieve property-like syntax using normal methods, sometimes with a limited amount of
syntactic sugar
In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an ...
.
Syntax variants
Some languages follow well-established syntax conventions for formally specifying and utilizing properties and methods.
Among these conventions:
* Dot notation
* Bracket notation
Dot notation
The following example demonstrates dot notation in JavaScript.
document.createElement('pre');
Bracket notation
The following example demonstrates bracket notation in JavaScript.
document createElement''pre');
Example syntax
C#
class Pen
// accessing:
Pen pen = new Pen();
int color_tmp = 0;
// ...
pen.Color = 17;
color_tmp = pen.Color;
// ...
pen.Color = ~pen.Color; // bitwise complement ...
// another silly example:
pen.Color += 1; // a lot clearer than "pen.set_Color(pen.get_Color() + 1)"!
Recent C# versions also allow "auto-implemented properties" where the backing field for the property is generated by the compiler during compilation. This means that the property must have a setter. However, it can be private.
class Shape
C++
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
does not have first class properties, but there exist several ways to emulate properties to a limited degree. Two of which follow:
Using Standard C++
#include
template class property ;
struct Foo ;
struct Bar ;
int main ()
Also se
Stack Overflowfor a more detailed example.
C++, Microsoft, GCC, LLVM/clang and C++Builder-specific
An example taken from the MSD
documentation page
// declspec_property.cpp
struct S
;
int main()
D
class Pen
auto pen = new Pen;
pen.color = ~pen.color; // bitwise complement
// the set property can also be used in expressions, just like regular assignment
int theColor = (pen.color = 0xFF0000);
In D version 2, each property accessor or mutator must be marked with @property:
class Pen
Delphi/Free Pascal
type TPen = class
private
FColor: TColor;
function GetColor: TColor;
procedure SetColor(const AValue: TColor);
public
property Color: Integer read GetColor write SetColor;
end;
function TPen.GetColor: TColor;
begin
Result := FColor;
end;
procedure TPen.SetColor(const AValue: TColor);
begin
if FColor <> AValue
then FColor := AValue;
end;
// accessing:
var Pen: TPen;
// ...
Pen.Color := not Pen.Color;
(*
Delphi and Free Pascal also support a 'direct field' syntax -
property Color: TColor read FColor write SetColor;
or
property Color: TColor read GetColor write FColor;
where the compiler generates the exact same code as for reading and writing
a field. This offers the efficiency of a field, with the safety of a property.
(You can't get a pointer to the property, and you can always replace the member
access with a method call.)
*)
eC
class Pen
Pen blackPen ;
Pen whitePen ;
Pen pen3 ;
Pen pen4 ;
F#
type Pen() = class
let mutable _color = 0
member this.Color
with get() = _color
and set value = _color <- value
end
let pen = new Pen()
pen.Color <- ~~~pen.Color
JavaScript
function Pen()
// Add the property to the Pen type itself, can also
// be set on the instance individually
Object.defineProperties(Pen.prototype, );
var pen = new Pen();
pen.color = ~pen.color; // bitwise complement
pen.color += 1; // Add one
ActionScript 3.0
package
var pen:Pen = new Pen();
pen.color = ~pen.color; // bitwise complement
pen.color += 1; // add one
Objective-C 2.0
@interface Pen : NSObject
@property (copy) NSColor *colour; // The "copy" attribute causes the object's copy to be
// retained, instead of the original.
@end
@implementation Pen
@synthesize colour; // Compiler directive to synthesise accessor methods.
// It can be left behind in Xcode 4.5 and later.
@end
The above example could be used in an arbitrary method like this:
Pen *pen = Pen allocinit];
pen.colour = SColor blackColor
float red = pen.colour.redComponent;
en.colour drawSwatchInRect: NSMakeRect(0, 0, 100, 100)
PHP
class Pen
$p = new Pen();
$p->color = ~$p->color; // Bitwise complement
echo $p->color;
Python
Properties only work correctly for new-style classes (classes that have
object
as a
superclass), and are only available in Python 2.2 and newer (se
the relevant section of the tutorial ''Unifying types and classes in Python 2.2''. Python 2.6 added a new syntax involving decorators for defining properties.
class Pen:
def __init__(self) -> None:
self._color = 0 # "private" variable
@property
def color(self):
return self._color
@color.setter
def color(self, color):
self._color = color
pen = Pen()
# Accessing:
pen.color = ~pen.color # Bitwise complement ...
Ruby
class Pen
def initialize
@color = 0
end
# Defines a getter for the @color field
def color
@color
end
# Defines a setter for the @color field
def color=(value)
@color = value
end
end
pen = Pen.new
pen.color = ~pen.color # Bitwise complement
Ruby also provides automatic getter/setter synthesizers defined as instance methods of Class.
class Pen
attr_reader :brand # Generates a getter for @brand (Read-Only)
attr_writer :size # Generates a setter for @size (Write-Only)
attr_accessor :color # Generates both a getter and setter for @color (Read/Write)
def initialize
@color = 0 # Within the object, we can access the instance variable directly
@brand = "Penbrand"
@size = 0.7 # But we could also use the setter method defined by the attr_accessor Class instance method
end
end
pen = Pen.new
puts pen.brand # Accesses the pen brand through the generated getter
pen.size = 0.5 # Updates the size field of the pen through the generated setter
pen.color = ~pen.color
Visual Basic
Visual Basic (.NET 2003–2010)
Public Class Pen
Private _color As Integer ' Private field
Public Property Color() As Integer ' Public property
Get
Return _color
End Get
Set(ByVal value As Integer)
_color = value
End Set
End Property
End Class
' Create Pen class instance
Dim pen As New Pen()
' Set value
pen.Color = 1
' Get value
Dim color As Int32 = pen.Color
Visual Basic (only .NET 2010)
Public Class Pen
Public Property Color() As Integer ' Public property
End Class
' Create Pen class instance
Dim pen As New Pen()
' Set value
pen.Color = 1
' Get value
Dim color As Int32 = pen.Color
Visual Basic 6
' in a class named clsPen
Private m_Color As Long
Public Property Get Color() As Long
Color = m_Color
End Property
Public Property Let Color(ByVal RHS As Long)
m_Color = RHS
End Property
' accessing:
Dim pen As New clsPen
' ...
pen.Color = Not pen.Color
See also
*
Attribute (computing)
In computing, an attribute is a specification that defines a property of an object, element, or file. It may also refer to or set the specific value for a given instance of such. For clarity, attributes should more correctly be considered meta ...
*
Bound property
*
Field (computer science)
In computer science, data that has several parts, known as a '' record,'' can be divided into fields (data fields). Relational databases arrange data as sets of database records, so called rows. Each record consists of several ''fields''; the fi ...
*
Indexer (programming)
In object-oriented programming, an indexer allows instances of a particular class or struct to be indexed just like arrays. It is a form of operator overloading.
Implementation
Indexers are implemented through the get and set accessors for the ...
*
Method (computer programming)
A method in object-oriented programming (OOP) is a procedure associated with a message and an object. An object consists of ''state data'' and ''behavior''; these compose an ''interface'', which specifies how the object may be utilized by any of ...
*
Mutator method In computer science, a mutator method is a method used to control changes to a variable. They are also widely known as setter methods. Often a setter is accompanied by a getter (together also known as accessors), which returns the value of the priva ...
*
Uniform access principle
The uniform access principle of computer programming was put forth by Bertrand Meyer (originally in ''Object-Oriented Software Construction''). It states "All services offered by a module should be available through a uniform notation, which does ...
References
{{DEFAULTSORT:Property (Programming)
Object-oriented programming
Articles with example PHP code
Articles with example Python (programming language) code
Articles with example Ruby code