Property (programming)

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

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

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 
{
    private int color; // private field
    
    // public property
    public int Color 
    {  
        get
        {
            return this.color;
        }
        set 
        {
            if (value > 0) {
                this.color = value;
            }
        }
    }
}
// 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 
{
    public int Height { get; set; }
    public int Width { get; private set; }
}

C++

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

#include <iostream>

template <typename T> class property {
        T value;
    public:
        T & operator = (const T &i) {
            return value = i;
        }
        // This template class member function template serves the purpose to make
        // typing more strict. Assignment to this is only possible with exact identical types.
        // The reason why it will cause an error is temporary variable created while implicit type conversion in reference initialization.
        template <typename T2> T2 & operator = (const T2 &i) {
            T2 &guard = value;
            throw guard; // Never reached.
        }

        // Implicit conversion back to T. 
        operator T const & () const {
            return value;
        }
};

struct Foo {
    // Properties using unnamed classes.
    class {
            int value;
        public:
            int & operator = (const int &i) { return value = i; }
            operator int () const { return value; }
    } alpha;

    class {
            float value;
        public:
            float & operator = (const float &f) { return value = f; }
            operator float () const { return value; }
    } bravo;
};

struct Bar {
    // Using the property<>-template.
    property <bool> alpha;
    property <unsigned int> bravo;
};

int main () {
    Foo foo;
    foo.alpha = 5;
    foo.bravo = 5.132f;

    Bar bar;
    bar.alpha = true;
    bar.bravo = true; // This line will yield a compile time error
                      // due to the guard template member function.
    ::std::cout << foo.alpha << ", "
                << foo.bravo << ", "
                << bar.alpha << ", "
                << bar.bravo
                << ::std::endl;
    return 0;
}

Also see Stack Overflow for a more detailed example.

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

An example taken from the MSDN documentation page.

// declspec_property.cpp
struct S
{
   int i;
   void putprop(int j)
   { 
      i = j;
   }

   int getprop()
   {
      return i;
   }

   __declspec(property(get = getprop, put = putprop)) int the_prop;
};

int main()
{
   S s;
   s.the_prop = 5;
   return s.the_prop;
}

D

class Pen
{
    private int m_color; // private field
    
    // public get property
    public int color () {
        return m_color;
    }
    
    // public set property
    public void color (int value) {
         m_color = value;
    }
}
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
{
    private int m_color; // private field
    
    // public get property
    @property public int color () {
        return m_color;
    }
    
    // public set property
    @property public void color (int value) {
        m_color = value;
    }
}

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 
{
   // private data member
   Color color;
public:
   // public property
   property Color color 
   {  
      get { return color; }
      set { color = value; }
   }
}
Pen blackPen { color = black };
Pen whitePen { color = white };
Pen pen3 { color = { 30, 80, 120 } };
Pen pen4 { color = ColorHSV { 90, 20, 40 } };

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() {
    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 () {
            return this._color;
        },
        set: function (value) {
            this._color = value;
        }
    }
});
var pen = new Pen();
pen.color = ~pen.color; // bitwise complement
pen.color += 1; // Add one

ActionScript 3.0

package {
	public class Pen {
		private var _bitcoin. = 0;
		
		public function get wight ():uint {
			return _bitcoin/;
		}
		
		public function set color(value:uint):void {
			_color = value;
		}
	}
}
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 alloc] init];
pen.colour = [NSColor blackColor];
float red = pen.colour.redComponent;
[pen.colour drawSwatchInRect: NSMakeRect(0, 0, 100, 100)];

PHP

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

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.

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

References

  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.

Read other articles:

City in Washington, United States City in Washington, United StatesPort AngelesCityAerial view of downtown Port Angeles, looking towards the Olympic MountainsMotto: Where the mountains meet the sea.Location of Port Angeles in Clallam County and the state of WashingtonPort AngelesLocation of Port AngelesShow map of Washington (state)Port AngelesPort Angeles (the United States)Show map of the United StatesCoordinates: 48°06′47″N 123°26′27″W / 48.11306°N 123.44083...

 

Alosa braschnikowi Estado de conservação Dados Deficientes (IUCN 3.1)[1] Classificação científica Domínio: Eukaryota Reino: Animalia Filo: Chordata Classe: Actinopterygii Ordem: Clupeiformes Família: Alosidae Gênero: Alosa Espécies: A. braschnikowi Nome binomial Alosa braschnikowi(Borodin, 1904) Alosa braschnikowi é uma espécie de peixe da família Clupeidae no ordem dos Clupeiformes. Morfologia • Os machos podem atingir 50 cm de comprimento total. Dentes bem desen...

 

General Ice Cream Corporation Building Lugar inscrito en el Registro Nacional de Lugares Históricos LocalizaciónPaís Estados UnidosUbicación Rhode IslandCoordenadas 41°48′47″N 71°27′19″O / 41.813056, -71.455278[editar datos en Wikidata] El General Ice Cream Corporation Building es un edificio industrial histórico en 485 Plainfield Street en el vecindario Silver Lake de la ciudad Providence, la capital del estado de Rhode Island (Estados Unidos). Descri...

Nationale Eisenbahn des Kongo Gare de LubumbashiGare de LubumbashiStrecke der Société Nationale des Chemins de fer du CongoDas theoretische Streckennetz der SNCCStreckenlänge:5033,0 kmStromsystem:25 kV 1/50 Hz ~Höchstgeschwindigkeit:15[1] km/h Die Société Nationale des Chemins de fer du Congo (Nationale Eisenbahngesellschaft des Kongo, abgekürzt SNCC) ist ein staatliches Unternehmen der Demokratischen Republik Kongo zum Betrieb von Eisenbahnen, Häfen, Schifffahr...

 

Triller berekor panjang Status konservasi Risiko Rendah (IUCN 3.1)[1] Klasifikasi ilmiah Kerajaan: Animalia Filum: Chordata Kelas: Aves Ordo: Passeriformes Famili: Campephagidae Genus: Lalage Spesies: 'L. leucopyga' Nama binomial Lalage leucopyga(Gould, 1838) Subspesies[2] Lalage leucopyga leucopyga: Norfolk I. Extinct Lalage leucopyga montrosieri: New Caledonia Lalage leucopyga affinis: Solomon Islands (Makira and Ugi) Lalage leucopyga deficiens: Vanuatu (Torres I. ...

 

Kristal lisozim. Struktur lisozim berdasarkan analisis dengan sinar-X Lisozim adalah enzim yang memutuskan ikatan β-1,4-glikosida antara asam-N-asetil glukosamin dengan asam-N-asetil muramat pada peptidoglikan sehingga dapat merusak dinding sel bakteri.[1] Air kemudian dapat masuk ke dalam sel dan menyebabkan sel menggelembung dan akhirnya pecah, proses tersebut disebut dengan lisis.[1] Lisozim dapat ditemukan pada sekresi hewan termasuk air mata, saliva, dan cairan tubuh yan...

2013 compilation album by Various artistsLet Us in Americana: The Music of Paul McCartneyCompilation album by Various artistsReleasedJune 23, 2013GenreAmericana[1][2]LabelReviver RecordsProducerPhil Madeira, Executive: Chris Ford, David Ross, Dennis D’Amico Let Us in Americana: The Music of Paul McCartney is a tribute album to musician Paul McCartney.[1] Phil Madeira produced the album,[2] released by Reviver Records in 2013.[1] All the procee...

 

For older awards, see Awards and decorations of the Ukrainian Armed Forces (before 2012). Awards and decorations of the Ukrainian Armed Forces are military decorations issued by the Ministry of Defence of Ukraine to soldiers who achieve a variety of qualifications, who have completed classroom training standards stipulated in their military occupational specialty and accomplishments while serving on active and reserve duty in the Armed Forces of Ukraine. Together with military badges, medals ...

 

Transportation in MontanaConstruction sign for I-90 in Montana during the mid-20th centuryOverviewTransit typeRapid transit, commuter rail, buses, private automobile, taxicab, bicycle, pedestrian, highwaysWebsitehttp://www.mdt.mt.gov/OperationOperator(s)Montana Department of Transportation Main highways map Transportation in Montana comprises many different forms of travel. Montana shares a long border with Canada, hence international crossings are prevalent in the northern section of the sta...

Гомогенність, гетерогенність. Гетероге́нні (неоднорідні) систе́ми — фізико-хімічні системи, що складаються з двох або кількох фаз, наприклад, система: «лід — вода — водяна пара» — гетерогенна система з трьох фаз. Зміст 1 Опис 2 Класифікація 3 Методи розділення ...

 

County in Oklahoma, United States County in OklahomaNowata CountyCountyNowata County Courthouse in Nowata (2016)Location within the U.S. state of OklahomaOklahoma's location within the U.S.Coordinates: 36°47′N 95°37′W / 36.79°N 95.62°W / 36.79; -95.62Country United StatesState OklahomaFounded1907SeatNowataLargest cityNowataArea • Total581 sq mi (1,500 km2) • Land566 sq mi (1,470 km2) • ...

 

The Dickson Poon School of Law,King's College LondonFormer namesFaculty of Laws, King's College, London (1909–1991)King's College London School of Law (1991–2012)Established1831Parent institutionKing's College LondonDeanDan Hunter[1]Academic staff228[2]Students1,976[2]LocationSomerset House East Wing, London, United KingdomWebsitekcl.ac.uk/law The Dickson Poon School of Law is the law school of King's College London, itself part of the federal University of London,...

National Scouting organization of Burundi Association des Scouts du BurundiScout Association of BurundiCountryBurundiFounded1940Membership104,874 (2021)AffiliationWorld Organization of the Scout Movement Websitehttps://web.archive.org/web/20110904125500/http://scoutsburundi.org/ Scouting portal The Association des Scouts du Burundi, the national Scouting organization of Burundi, was founded in 1940, and became a member of the World Organization of the Scout Movement in 1979. The coeducat...

 

1993 Indian filmPurusha LakshanamVCD coverDirected byK. S. RavikumarScreenplay byK. S. RavikumarStory byP. VasuProduced byM. NarendiranStarringJayaramKhushbuCinematographyAshok RajanEdited byK. ThanikachalamMusic byDevaProductioncompanyGood Luck FilmsRelease date 3 December 1993 (1993-12-03) CountryIndiaLanguageTamil Purusha Lakshanam is a 1993 Indian Tamil-language drama film, written and directed by K. S. Ravikumar from a story by P. Vasu. The film stars Jayaram and Khushbu. ...

 

Private Catholic high school in Oxnard, California Santa Clara High SchoolAddress2121 Saviers RoadOxnard, Ventura, California 93033United StatesCoordinates34°10′43″N 119°10′42″W / 34.17861°N 119.17833°W / 34.17861; -119.17833InformationTypePrivate, CoeducationalMottoIn Hoc Signo Vinces(With This Sign We Conquer)Religious affiliation(s)Roman CatholicPatron saint(s)St. Clare of AssisiEstablished1901; 122 years ago (1901)FounderSanta Clara Pa...

Norman language dialect 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: Cotentinais – news · newspapers · books · scholar · JSTOR (October 2022) (Learn how and when to remove this template message) CotentinaisMap of Cotentin peninsulaRegionCotentin PeninsulaLanguage familyIndo-European ItalicLatino-FaliscanL...

 

The Central Federation League is an amateur status league competition run by Central Football for association football clubs located in the central region of the North Island, New Zealand. It is currently in the third level of the New Zealand football league system, below the Central League administered by Capital Football and is entered by clubs from the Taranaki, Manawatū-Whanganui, Hawke's Bay and Gisborne districts. Football leagueCentral Federation LeagueFounded2000CountryNew ZealandCon...

 

Questa voce o sezione sull'argomento film è priva o carente di note e riferimenti bibliografici puntuali. Sebbene vi siano una bibliografia e/o dei collegamenti esterni, manca la contestualizzazione delle fonti con note a piè di pagina o altri riferimenti precisi che indichino puntualmente la provenienza delle informazioni. Puoi migliorare questa voce citando le fonti più precisamente. Segui i suggerimenti del progetto di riferimento. Il paese di PaperinoTitolo italiano del filmTitolo...

Ichita Yamamoto山本一太Yamamoto di Filipina Konselor untuk Distrik besar GunmaPetahanaMulai menjabat 2005–sekarangPerdana MenteriShinzō Abe PendahuluGiichi TsunodaTomio YamamotoPenggantiPetahana Informasi pribadiLahir山本 一太 (Yamamoto Ichitacode: ja is deprecated )24 Januari 1958 (umur 66)Kusatsu, Gunma, JepangAlma materUniversitas ChuoSunting kotak info • L • B Ichita Yamamoto (山本 一太code: ja is deprecated , Yamamoto Ichita, kelahiran 24 Januari 195...

 

Schützenpanzer (lang) HS 30 HS 30 im Panzermuseum Thun Allgemeine Eigenschaften Besatzung 3 (Kommandant, Fahrer, Richtschütze) + weiteres Personal je nach Version Länge 5,56 m Breite 2,54 m Höhe 1,85 m Masse 14,37 t Panzerung und Bewaffnung Hauptbewaffnung 20-mm-Maschinenkanone HS 820 L/85 Sekundärbewaffnung keine Beweglichkeit Antrieb Achtzylinder-V-Motor, Ottomotor Typ Rolls-RoyceB81 Mk. 80 F164 kW (220 PS) Federung Schraubenfedern mit Gummifedertellern[1] Geschwindigkeit 58&#...

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!