Search This Blog

Monday, July 31, 2023

Causes of sexual violence

From Wikipedia, the free encyclopedia

There are many theories explaining the causes of sexual violence. These theories include military conquest, socioeconomics, anger, power, sadism, traits, ethical standards, laws, and evolutionary pressures that lend some explanation to the causes of sexual violence (such as rape, molestation, sexual harassment, stalking, etc.). Most of the research on the causes of sexual violence has only been done on male offenders (and has largely ignored female perpetrated sexual violence due to lack of data) and has been target of criticism.

Types of rapists

Clinical psychologist Nicholas Groth has described several different types of rape. A detailed conceptual analysis shows that objectification might underlie denial of agency and personhood that leads to rape.

Anger rapists

The goal of these rapists is to humiliate, debase and hurt their victims. They use an excessive amount of force, whether or not victims resist. Also, they express their contempt for their victims through physical violence and profane language. For these rapists, sex is a weapon to defile and degrade the victim, rape constitutes the ultimate expression of their anger. This rapist considers rape the ultimate offense they can commit against the victim. Friends and acquaintances of anger rapists may report a dark side to their personalities or lifestyles.

Anger rape is characterized by physical brutality: much more physical force is used during the assault than would be necessary if the intent were simply to overpower the victim and achieve penetration. This type of offender attacks their victim by grabbing, striking and knocking the victim to the ground, beating them, tearing their clothes, and raping them.

The experience for the offender is one of conscious anger and rage.

Power assertive rapist

For these rapists, rape becomes a way to compensate for their underlying feelings of inadequacy and feeds their issues of mastery, control, dominance, strength, intimidation, authority and capability. The intent of the power rapist is to assert their competency. The power rapist relies upon verbal threats, intimidation with a weapon, and only uses the amount of force necessary to subdue the victims. Rapes committed by this perpetrator are more impulsive, spontaneous, and unplanned. Victims are frequently encountered by coincidence, such as at pubs, clubs, or parties. Their attack is characterized by a modest level of force applied over a brief period of time. Unlike the power reassurance rapist, the power assertive rapist sees himself as a "macho man" who wants to prove his virility to women. His language is abrasive and laced with profanities.

The power rapist often will assume that the assault was not an assault because of their rape supportive attitudes. Power rapists are often in a mind set that they are entitled to their own pleasure regardless of the victims feelings or lack of desire. In the article, "Sexual Perpetrators' Justifications for Their Actions", it says, "One perpetrator who forced his steady dating partner to have sex after she willingly touched his penis, said 'I felt as if I had gotten something that I was entitled to. And I felt like I was repaying her for sexually arousing me'."

There is a clear tendency for a rapist to have fantasies about sexual experiences and assume that they are enjoying it or grateful for it even when they resist. Because this is only a fantasy, the rapist does not feel reassured for long by either their own performance or the victim's response. The rapist feels that they must find another victim, convinced that this victim will be "the right one". Hence, their offenses may become repetitive and compulsive. They may commit a series of rapes over a short period of time.

Sadistic rapists

These rapists have a sexual association with anger and power so that aggression and the infliction of pain itself are eroticized. For this rapist, sexual excitement is associated with the inflicting of pain upon their victim. The offender finds the intentional maltreatment of their victim intensely gratifying and takes pleasure in the victim's torment, pain, anguish, distress, helplessness, and suffering; they find the victim's struggling with them to be an erotic experience.

The sadistic rapist's assaults are deliberate, calculated, and preplanned. They will often wear a disguise or will blindfold their victims. Prostitutes or other people whom they perceive to be vulnerable are often the sadistic rapist's targets. The victims of a sadistic rapist may not survive the attack. For some offenders, the ultimate satisfaction is gained from murdering the victim.

The propensity models of sexual aggression

The propensity approach to sexual aggression focuses on the traits (features that are stable and fixed over time) that can increase the probability that someone will commit an act of sexual violence.

Cognitive and attitudinal biases

The cognitive traits and attitudinal biases associated with a propensity to commit acts of sexual aggression come from socio-cultural research and says that forms of sexual aggression come from false beliefs of gender relations, misdirected objectives (i.e. only dating to have sex), and erroneous impressions of social interactions (linked to gender relations). Research focusing specifically on gender relations within the context of sexual assault have found that conformance to notions of male entitlement, suspicion of the opposite sex, perceiving violence as a reasonable method for solving problems, and holding the traditional patriarchal attitudes that specific societal roles belong to specific genders are found to adhere to the concept of male entitlement/superiority (in the context of gender relations). The cognitive biases that add to one's propensity to commit acts of sexual violence include a feeling of entitlement (entitlement to sex), and the beliefs that women are sex objects, men's sexual drive is uncontrollable, society is dangerous, and women are unpredictable and dangerous.

Neuropsychological processes

The neuropsychological deficits that may contribute to a propensity for sexual assault include difficulties in self-regulation, executive functioning problems, perception/memory system problems, arousal/motivation system deficits, and problems in the action selection system. The difficulties arise when sexual aggressors are not able to understand their emotional states so that when confronted with a situation that trigger their arousal/motivation systems, they become confused and may have issues controlling their behavior. An inability to adapt plans to deal with unforeseen situations or having limited problem-solving skills (the action selection system) and maintaining maladaptive beliefs categorized by erroneous interpretations of social encounters (perception/memory systems) can also contribute to a greater tendency to commit acts of sexual violence.

Deviant sexual preferences

Research focusing on the deviant sexual preferences propensity model suggests that people who perpetrate acts of sexual violence are sexually aroused by non-consensual sexual interactions more than consensual sexual interactions. The research that seeks to support this model (penile plethysmography) has not been able to reliably find differences in the two different groups of males (those who have committed acts of sexual aggression and those who have not). Instead, the studies are providing more evidence for the cognitive, attitudinal, neuropsychological, and lifestyle differences that impact sexual arousal in certain situations, rather than a deviant sexual preference leading to a higher propensity for sexual violence.

Personality disorders and traits

The last propensity model of sexual violence views the perpetrators of sexual violence through three lenses of different personality traits, with interpersonal functioning being the most important factor in whether a person will have a higher propensity for sexual violence. This model is based on the idea that sexual aggression is indicative of problems starting and managing enjoyable intimate relationships.

Insecure attachment lens

The insecure attachment style lens stems from research done on sexual aggressors that characterized them as people who had insecure attachment styles (as a result of child abuse, parental divorce, etc.) manifested as low self-esteem, an inability to develop relationships with others, and significant emotional loneliness. Through the lens of this model, sexual aggression is used as a faulty means of fulfilling intimacy needs.

Antisocial personality traits/quadripartite lens

The antisocial personality lens stems from a study done by Hall and Hirschman (1991) and emphasizes the subsequent consequences of experiencing adversities/abuses in childhood, which can lead to the development of antisocial personality traits in adulthood. The antisocial personality traits combine with contextual, emotional (rage/anger), cognitive (irrational thoughts that influence emotions), and physiological (deviant sexual arousal) factors that increase the probability of committing sexual violence.

Narcissistic personality lens

Lastly, the narcissistic lens emphasizes the assumption that individuals with narcissistic personality traits are more likely to interpret refusal of sexual advances as insults, and in turn will have an adverse reaction to such insults (narcissistic injury). This lens is best used when describing sexual violence that includes known victims (such as incest, date rape, domestic abuse, etc.) because it is not able to adequately explain sexual violence such as stranger rape.

Individual factors

Known victim

Data on sexually violent individuals show that most direct their acts at individuals whom they already know.

Drug-facilitated sexual assault

Drug-facilitated sexual assault (DFSA), also known as predator rape, is a sexual assault carried out after the victim has become incapacitated due to having consumed alcoholic beverages or other drugs. Alcohol has been shown to play a disinhibiting role in certain types of sexual assault, as have some other drugs, notably cocaine. Alcohol has a psychopharmacological effect of reducing inhibitions, clouding judgements and impairing the ability to interpret cues. The biological links between alcohol and violence are, however, complex. Research on the social anthropology of alcohol consumption suggests that connections between violence, drinking and drunkenness are socially learned rather than universal. Some researchers have noted that alcohol may act as a cultural break time, providing the opportunity for antisocial behavior. Judgments are more likely to act violently when drunk because they do not consider that they will be held accountable for their behavior. Some forms of group sexual violence are also associated with drinking. In these settings, consuming alcohol is an act of group bonding, where inhibitions are collectively reduced and individual judgment ceded in favor of the group.

Sexual gratification

In 1994, Richard Felson and James Tedeschi coauthored the controversial book Aggression and Coercive Actions: A Social-Interactionist Perspective, which argues that rapists are motivated by sexual entitlement, rather than the aggressive desire to dominate the victim. Felson believes that rape is an aggressive form of sexual coercion and the goals of rape are sexual entitlement and gaining a sense of power. Meta-analyses indicate that convicted rapists demonstrate greater sexual arousal to scenes of sexual coercion involving force than do non-rapists. In one study, male rapists evaluated with penile plethysmography demonstrated more arousal to forced sex and less discrimination between forced and consensual sex than non-rapist control subjects, though both groups responded more strongly to consensual sex scenarios.

Psychological factors

There has been considerable research in recent times on the role of cognitive variables among the set of factors that can lead to rape. A detailed conceptual analysis shows that objectification might underlie denial of agency and personhood that leads to rape. Sexually violent men have been shown to be more likely to consider victims responsible for the rape and less knowledgeable about the impact of rape on victims. Such men may misread cues given out by women in social situations and may lack the inhibitions that act to suppress associations between sex and aggression. They may have coercive sexual fantasies, and overall are more hostile towards women than men who are not sexually violent. In addition to these factors, sexually violent men are believed to differ from other men in terms of impulsivity and antisocial tendencies. They also tend to have an exaggerated sense of masculinity. Sexual violence is also associated with a preference for impersonal sexual relationships as opposed to emotional bonding, with having many sexual partners and with the inclination to assert personal interests at the expense of others. A further association is with adversarial attitudes on gender, which hold that women are opponents to be challenged and conquered.

Research on convicted rapists

The research on convicted rapists has found several important motivational factors in the sexual aggression of males. Those motivational factors repeatedly implicated are having anger at women and having the need to control or dominate them.

A study by Marshall et al. (2001) found that male rapists had less empathy toward women who had been sexually assaulted by an unknown assailant and more hostility toward women than non-sex-offenders and nonoffender males/females.

Meta-analyses indicate that convicted rapists demonstrate greater sexual arousal to scenes of sexual coercion involving force than do non-rapists.

Social factors

Factors operating at a societal level that influence sexual violence include laws and national policies relating to gender equality in general and to sexual violence more specifically, as well as norms relating to the use of violence. While the various factors operate largely at local level, within families, schools, workplaces and communities, there are also influences from the laws and norms working at national and even international levels.

Family and other social supports

Early childhood environments

There is evidence to suggest that sexual violence is also a learned behavior in some adults, particularly in regard to child sexual abuse. Studies on sexually abused boys have shown that around one in five later molest children themselves.

Childhood environments that are physically violent, emotionally unsupportive and characterized by competition for scarce resources have been associated with sexual violence. Sexually aggressive behavior in young men, for instance, has been linked to witnessing family violence, and having emotionally distant and uncaring fathers. Men raised in families with strongly patriarchal structures are also more likely to become violent, to rape and use sexual coercion against women, as well as to abuse their intimate partners, than men raised in homes that are more egalitarian.

Family honor and sexual purity

Another factor involving social relationships is a family's response that blames women without punishing men, concentrating instead on restoring lost family honor. Such a response creates an environment in which rape can occur with impunity.

While families will often try to protect female members from rape and may also put their daughters on contraception to prevent visible signs should it occur, there is rarely much social pressure to control young men or persuade them that coercing sex is wrong. Instead, in some countries, there is frequently support for family members to do whatever is necessary, including murder, to alleviate the shame associated with a rape or other sexual transgression. In a review of all honor killings occurring in Jordan in 1995, researchers found that in over 60% of the cases, the victim died from multiple gunshot wounds, mostly at the hands of a brother. In cases where the victim was a single pregnant woman, the offender was either acquitted of murder or received a reduced sentence.

Social stressors

War and natural disasters

Lawlessness during wars and civil conflicts can create a culture of impunity towards human rights abuses of civilians. Some irregular armies and militias tacitly endorse looting of civilian areas as a way for troops to supplement their meagre incomes, and promote pillaging and rape of civilians as a reward for victory. In 2008, the United Nations Security Council argued that "women and girls are particularly targeted by the use of sexual violence, including as a tactic of war to humiliate, dominate, instil fear in, disperse and/or forcibly relocate civilian members of a community or ethnic group."

Refugees and internally displaced people who flee their homes during war and major disasters can experience human trafficking for sexual or labour exploitation due to the breakdown of economies and law and order. Speaking at the UN General Assembly in 2010, the UN Special Rapporteur on Violence Against Women, its Causes and Consequences noted women's particular vulnerability and increased risk of experiencing violence following disasters. Following the 2010 Haiti earthquake, large numbers of women and girls living in Internally Displaced Persons camps experienced sexual violence. The Inter-American Commission on Human Rights recognized the need for state actors to respond to gender-based violence committed by private actors, in response to a petition by Haitian groups and human rights lawyers calling on the Haitian government and international actors to take immediate measures—like increasing lighting, security, and access to medical care—to address sexual violence against women and girls in the IDP camps.

Poverty

Poverty is linked to both the perpetration of sexual violence and the risk of being a victim of it. Several authors have argued that the relationship between poverty and perpetration of sexual violence is mediated through forms of crisis of masculine identity.

Bourgois, writing about life in East Harlem, New York, United States, described how young men felt pressured by models of successful masculinity and family structure passed down from their parents' and grandparents' generations, together with modern-day ideals of manhood that also place an emphasis on material consumption. Trapped in their slums, with little or no available employment, they are unlikely to attain either of these models or expectations of masculine success. In these circumstances, ideals of masculinity are reshaped to emphasize misogyny, substance abuse and participation in crime and often also xenophobia and racism. Gang rape and sexual conquest are normalized, as men turn their aggression against women they can no longer control patriarchally or support economically.

Physical environment

While fear of rape is typically associated with being outside the home, the great majority of sexual violence actually occurs in the home of the victim or the abuser. Nonetheless, abduction by a stranger is quite often the prelude to a rape and the opportunities for such an abduction are influenced by the physical environment. The social environment within a community is, however, usually more important than the physical surrounding. How deeply entrenched in a community beliefs in male superiority and male entitlement to sex are will greatly affect the likelihood of sexual violence taking place, as will the general tolerance in the community of sexual assault and the strength of sanctions, if any, against perpetrators. For instance, in some places, rape can even occur in public, with passersby refusing to intervene.

Legal and social deterrents of victims reporting sexual assault

Women in various countries face serious risks if they report rape. These risks include being subjected to violence (including honor killings) by their families, being prosecuted for sex outside marriage, or being forced to marry their rapist. This creates a culture of impunity that allows rape to go unpunished. "Delegation clauses" used in many nursing home contracts have been blamed for effectively permitting the rape of residents.

Social norms

Sexual violence committed by men is to a large extent rooted in ideologies of male sexual entitlement. These belief systems grant women extremely few legitimate options to refuse sexual advances. Some men thus simply exclude the possibility that their sexual advances towards a woman might be rejected or that a woman has the right to make an autonomous decision about participating in sex. In some cultures women, as well as men, regard marriage as entailing the obligation on women to be sexually available virtually without limit, though sex may be culturally proscribed at certain times, such as after childbirth or during menstruation.

Societal norms around the use of violence as a means to achieve objectives have been strongly associated with the prevalence of rape. In societies with a machismo ideology - emphasizing dominance, physical strength and male honor - rape is more common. Countries with a culture of violence, or where violent conflict is taking place, experience an increase in almost all forms of violence, including sexual violence.

Economic factors

Many of the factors operating at a national level have an international dimension. Global trends, for instance towards free trade, have been accompanied by an increase in the movement around the world of women and girls for labor, including for sex work. Economic structural adjustment programmes, drawn up by international agencies, have accentuated poverty and unemployment in a number of countries, thereby increasing the likelihood of sexual trafficking and sexual violence, something particularly noted in Central America, the Caribbean and parts of Africa.

Social climate theories

Feminist theories of male-female rape

A feminist theory of male-female rape is summarized by Susan Brownmiller's statement: "rape is nothing more or less than a conscious process of intimidation by which all men keep all women in a state of fear". Some feminists assert that male domination of women in socio-political and economic domains is the ultimate cause of most rapes, and consider male-female rape to be a crime of power that has little or nothing to do with sex itself. However, a 1983 study comparing 14 indicators of male dominance and the incidence of rape in 26 American cities found no correlations, except one where greater male dominance actually decreased the incidence of rape. Social learning theory of rape is similar to the feminist theory and links cultural traditions such as imitation, sex-violence linkages, rape myths (e.g., "women secretly desire to be raped"), and desensitization to be the core causes of rape.

Rape culture

Rape culture is a term used within women's studies and feminism, describing a culture in which rape and other sexual violence (usually against women) are common and in which prevalent attitudes, norms, practices, and media condone, normalize, excuse, or encourage sexualized violence.

Within the paradigm, acts of sexism are commonly employed to validate and rationalize normative misogynistic practices; for instance, sexist jokes may be told to foster disrespect for women and an accompanying disregard for their well-being, which ultimately make their rape and abuse seem "acceptable". Examples of behaviors said to typify rape culture include victim blaming, trivializing prison rape, and sexual objectification.

Rape culture as a concept and social reality was explored in detail in the 1975 film Rape Culture, produced by Margaret Lazarus and Renner Wunderlich for Cambridge Documentary Films.

Gender based socialization and sexual scripts

Studies of college-aged sexually active men and women show they often conceptualize men as sexual initiators and women as sexual gatekeepers.

It has been argued that sexual assault trials, as well as rape itself, may be influenced by cultural narratives of men as sexual instigators. Boys are brought up to be sexually aggressive, dominant and conquering, as a way of affirming their masculinity. Catharine MacKinnon argues that men rape "for reasons that they share in common even with those who don't, namely masculinity and their identification with masculine norms and in particular being the people who initiate sex and being the people who socially experience themselves as being affirmed by aggressive initiation of sexual interaction". According to Check and Malamuth (1983), men are taught to take the initiative and persist in sexual encounters, while women are supposed to set the limits. This classical sexual script is often popularized through television shows, popular films and pornography, which depict the man making a sexual advance and the woman initially resisting, but then finally positively responding by falling in love with him or experiencing orgasm (Cowen, Lee, Levy, and Snyder, 1988; Malamuth and Check, 1981; Smith, 1976; Waggett, 1989). The implied message is that men should persist beyond a woman's protest and women should say "no" even if they desire sex (Muehlenhard and McCoy, 1991). The more traditional the society, the closer the adherence to this sexual script. For this reason, many men do not believe that a woman means "no" when she says "no", and continue to pressure the woman, and ultimately coerce or force her into sex; consent often becomes confused with submission.

In many societies, men who do not act in a traditionally masculine way are ostracized by their peers and considered effeminate In studies, young males from Cambodia, Mexico, Peru and South Africa reported that they have participated in incidents where girls were coerced into sex (such as gang rapes) and that they did so as a way to prove their masculinity to their friends, or under peer pressure and fear that they would be rejected if they did not participate in the assault.

Sex industry and sexual assault

Some theorists charge that the acceptance of these sexual practices increase sexual violence against women, by reinforcing stereotypical views about women, who are seen as sex objects which can be used and abused by men, and by desensitizing men; this being one of the reasons why some theorists oppose the sex industry. They argue that pornography eroticizes the domination, humiliation, and coercion of women, and reinforces sexual and cultural attitudes that are complicit in rape and sexual harassment. The anti-pornography feminist, Andrea Dworkin, has famously argued this point in her controversial Pornography: Men Possessing Women (1981).

Evolutionary explanations

Males who under some circumstances used force may have had greater reproductive success in the ancestral environment than males who did not employ force. Sociobiological theories of rape are theories that explore to what degree, if any, evolutionary adaptations influence the psychology of rapists. Such theories are highly controversial, as traditional theories typically do not consider rape to be a behavioral adaptation. Some object to such theories on ethical, religious, political as well as scientific grounds. Others argue that a correct knowledge of the causes of rape is necessary in order to develop effective preventive measures. There is extensive research on sexual coercion.

Property (programming)

From Wikipedia, the free encyclopedia

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, 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.

Oberon-2 provides an alternative mechanism using object variable visibility flags.

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.

Also note that some C++ compilers support first class properties as language extensions.

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.

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

Operator (computer programming)

From Wikipedia, the free encyclopedia https://en.wikipedia.org/wiki/Operator_(computer_programmin...