Jump to content
Wikipedia The Free Encyclopedia

Property (programming)

From Wikipedia, the free encyclopedia
Class member in object-oriented programming
This article needs additional citations for verification . Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.
Find sources: "Property" programming – news · newspapers · books · scholar · JSTOR
(January 2022) (Learn how and when to remove this message)

A property, in some object-oriented programming languages, is a special sort of class member, intermediate in functionality between a field (or data member) and a method. The syntax for reading and writing of properties is like for fields, but property reads and writes are (usually) translated to 'getter' and 'setter' method calls. The field-like syntax is easier to read and write than many method calls,[citation needed ] yet the interposition of method calls "under the hood" allows for data validation, active updating (e.g., of GUI elements), or implementation of what may be called "read-only fields".

Support in languages

[edit ]

Programming languages that support properties include ActionScript 3, C#, D, Delphi/Free Pascal, eC, F#, Kotlin, JavaScript, Objective-C 2.0, Python, Scala, Swift, Lua, and Visual Basic.

Some object-oriented languages, such as Java and C++, do not support properties, requiring the programmer to define a pair of accessor and mutator methods instead.[1] [citation needed ]

Oberon-2 provides an alternative mechanism using object variable visibility flags.[citation needed ]

Other languages designed for the Java Virtual Machine, such as Groovy, natively support properties.

While C++ does not have first class properties, they can be emulated with operator overloading.[2]

Also note that some C++ compilers support first class properties as language extensions.[citation needed ]

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. [citation needed ]

Some languages (Ruby, Smalltalk) achieve property-like syntax using normal methods, sometimes with a limited amount of syntactic sugar.

Syntax variants

[edit ]

Some languages follow well-established syntax conventions for formally specifying and utilizing properties and methods.

Among these conventions:

  • Dot notation
  • Bracket notation

Dot notation

[edit ]

The following example demonstrates dot notation in JavaScript.

document.createElement("pre");

Bracket notation

[edit ]

The following example demonstrates bracket notation in JavaScript.

document["createElement"]("pre");

Example syntax

[edit ]

C#

[edit ]
classPen
{
privateintcolor;// private field

// public property
publicintColor
{
get
{
returnthis.color;
}
set
{
if(value>0)
{
this.color=value;
}
}
}
}
// accessing:
Penpen=newPen();
intcolorTmp=0;
// ...
pen.Color=17;
colorTmp=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.

classShape
{
publicintHeight{get;set;}
publicintWidth{get;privateset;}
}

C++

[edit ]
This section does not cite any sources . Please help improve this section by adding citations to reliable sources. Unsourced material may be challenged and removed. (October 2016) (Learn how and when to remove this message)
This article may be confusing or unclear to readers. Please help clarify the article. There might be a discussion about this on the talk page. (October 2016) (Learn how and when to remove this message)

C++ 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++

[edit ]
importstd;
usingstd::same_as;
template<typenameT>
classProperty{
Tvalue;
public:
// Ensure T and T2 are the same type
template<typenameU>
requiressame_as<T,U>
T&operator=(constU&i){
value=i;
return*this;
}
// Implicit conversion back to T. 
operatorTconst&()const{
returnvalue;
}
};
structFoo{
// Properties using unnamed classes.
class{
private:
intvalue;
public:
int&operator=(constint&i){
returnvalue=i;
}
intoperatorint()const{
returnvalue;
}
}alpha;
class{
private:
floatvalue;
public:
float&operator=(constfloat&f){
returnvalue=f;
}
floatoperatorfloat()const{
returnvalue;
}
}bravo;
};
structBar{
// Using the Property<>-template.
Property<bool>alpha;
Property<unsignedint>bravo;
};
intmain(intargc,char*argv[]){
Foofoo;
foo.alpha=5;
foo.bravo=5.132f;
Barbar;
bar.alpha=true;
bar.bravo=true;// This line will yield a compile time error due to the guard template member function.
std::println("{}, {}, {}, {}",foo.alpha,foo.bravo,bar.alpha,bar.bravo);
return0;
}

C++, Microsoft, GCC, LLVM/clang and C++Builder-specific

[edit ]

An example adapted from the MSDN documentation page.

// declspec_property.cpp
structInteger{
intvalue;
voidsetValue(intj){
value=j;
}
intgetValue(){
returni;
}
__declspec(property(get=getValue,put=setValue))
intprop;
};
intmain(){
Integers;
s.prop=5;
return0;
}

D

[edit ]
classPen{
privateintmyColor;// private field

// public get property
publicintcolor(){
returnmyColor;
}

// public set property
publicvoidcolor(intvalue){
myColor=value;
}
}
Penpen=newPen;
pen.color=~pen.color;// bitwise complement
// the set property can also be used in expressions, just like regular assignment
inttheColor=(pen.color=0xFF0000);

In D version 2, each property accessor or mutator must be marked with @property:

classPen{
privateintmyColor;// private field

// public get property
@property
publicintcolor(){
returnmyColor;
}

// public set property
@property
publicvoidcolor(intvalue){
myColor=value;
}
}

Delphi/Free Pascal

[edit ]
typeTPen=class
private
FColor:TColor;
functionGetColor:TColor;
procedureSetColor(constAValue:TColor);
public
propertyColor:IntegerreadGetColorwriteSetColor;
end;
functionTPen.GetColor:TColor;
begin
Result:=FColor;
end;
procedureTPen.SetColor(constAValue:TColor);
begin
ifFColor<>AValue
thenFColor:=AValue;
end;
// accessing:
varPen:TPen;
// ...
Pen.Color:=notPen.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

[edit ]
classPen
{
// private data member
Colorcolor;
public:
// public property
propertyColorcolor
{
get{returncolor;}
set{color=value;}
}
}
PenblackPen{color=black};
PenwhitePen{color=white};
Penpen3{color={30,80,120}};
Penpen4{color=ColorHSV{90,20,40}};

F#

[edit ]
typePen()=class
letmutable_color=0
memberthis.Color
withget()=_color
andsetvalue=_color<-value
end
letpen=newPen()
pen.Color<-~~~pen.Color

JavaScript

[edit ]
functionPen(){
this._color=0;
}
// Add the property to the Pen type itself, can also
// be set on the instance individually
Object.defineProperties(Pen.prototype,{
color:{
get:function(){
returnthis._color;
},
set:function(value){
this._color=value;
}
}
});
varpen=newPen();
pen.color=~pen.color;// bitwise complement
pen.color+=1;// Add one

ActionScript 3.0

[edit ]
package{
publicclassPen{
privatevar_color:uint=0;

publicfunctiongetcolor():uint{
return_color;
}

publicfunctionsetcolor(value:uint):void{
_color=value;
}
}
}
varpen:Pen=newPen();
pen.color=~pen.color;// bitwise complement
pen.color+=1;// add one

Objective-C 2.0

[edit ]
@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
@synthesizecolour;// 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=[[Penalloc]init];
pen.colour=[NSColorblackColor];
floatred=pen.colour.redComponent;
[pen.colourdrawSwatchInRect:NSMakeRect(0,0,100,100)];

PHP

[edit ]
class Pen
{
 private int $color = 1;
 function __set($property, $value)
 {
 if (property_exists($this, $property)) { 
 $this->$property = $value;
 }
 }
 function __get($property)
 {
 if (property_exists($this, $property)) {
 return $this->$property;
 }
 return null;
 }
}
$p = new Pen();
$p->color = ~$p->color; // Bitwise complement
echo $p->color;

Python

[edit ]

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 (see 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.

classPen:
 def__init__(self):
 self._color = 0 # "private" variable
 @property
 defcolor(self):
 return self._color
 @color.setter
 defcolor(self, color):
 self._color = color
pen = Pen()
# Accessing:
pen.color = ~pen.color # Bitwise complement ...

Ruby

[edit ]
classPen
definitialize
@color=0
end

# Defines a getter for the @color field
defcolor
@color
end
# Defines a setter for the @color field
defcolor=(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.

classPen
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)
definitialize
@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
putspen.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

[edit ]

Visual Basic (.NET 2003–2010)

[edit ]
PublicClassPen

Private_colorAsInteger' Private field
PublicPropertyColor()AsInteger' Public property
Get
Return_color
EndGet
Set(ByValvalueAsInteger)
_color=value
EndSet
EndProperty
EndClass
' Create Pen class instance
DimpenAsNewPen()
' Set value
pen.Color=1
' Get value
DimcolorAsInt32=pen.Color

Visual Basic (only .NET 2010)

[edit ]
PublicClassPen
PublicPropertyColor()AsInteger' Public property
EndClass
' Create Pen class instance
DimpenAsNewPen()
' Set value
pen.Color=1
' Get value
DimcolorAsInt32=pen.Color

Visual Basic 6

[edit ]
' in a class named clsPen
Privatem_ColorAsLong
PublicPropertyGetColor()AsLong
Color=m_Color
EndProperty
PublicPropertyLetColor(ByValRHSAsLong)
m_Color=RHS
EndProperty
' accessing:
DimpenAsNewclsPen
' ...
pen.Color=Notpen.Color

See also

[edit ]

References

[edit ]
  1. ^ "Accessors And Mutators In Java". C# Corner - Community of Software and Data Developers. Retrieved 5 January 2022.
  2. ^ "Portability of Native C++ properties". Stack Overflow. Stack Overflow. Retrieved 5 January 2022.
  3. ^ "property (C++)". Microsoft technical documentation. Microsoft. Retrieved 5 January 2022.
  4. ^ "clang::MSPropertyDecl Class Reference". Clang: a C language family frontend for LLVM. Retrieved 5 January 2022.
  5. ^ "__property Keyword Extension". Embarcadero/IDERA Documentation Wiki. Retrieved 5 January 2022.

AltStyle によって変換されたページ (->オリジナル) /