Search This Blog

Monday, July 18, 2022

Age of consent

From Wikipedia, the free encyclopedia

The age of consent is the age at which a person is considered to be legally competent to consent to sexual acts. Consequently, an adult who engages in sexual activity with a person younger than the age of consent is unable to legally claim that the sexual activity was consensual, and such sexual activity may be considered child sexual abuse or statutory rape. The person below the minimum age is considered the victim, and their sex partner the offender, although some jurisdictions provide exceptions through "Romeo and Juliet laws" if both participants are underage. One purpose of setting an age of consent is to protect an underage person from sexual advances.

The term age of consent typically does not appear in legal statutes. Generally, a law will establish the age below which it is illegal to engage in sexual activity with that person. It has sometimes been used with other meanings, such as the age at which a person becomes competent to consent to marriage, but consent to sexual activity is the meaning now generally understood. It should not be confused with other laws regarding age minimums including, but not limited to, the age of majority, age of criminal responsibility, voting age, drinking age, and driving age.

Age of consent laws vary widely from jurisdiction to jurisdiction, though most jurisdictions set the age of consent in the range 14 to 18. The laws may also vary by the type of sexual act, the gender of the participants or other considerations, such as involving a position of trust; some jurisdictions may also make allowances for minors engaged in sexual acts with each other, rather than a single age. Charges and penalties resulting from a breach of these laws may range from a misdemeanor, such as corruption of a minor, to what is popularly called statutory rape.

There are many "grey areas" in this area of law, some regarding unspecific and untried legislation, others brought about by debates regarding changing societal attitudes, and others due to conflicts between federal and state laws. These factors all make age of consent an often confusing subject and a topic of highly charged debates.

By continent

Map of the world's countries, with countries colored by age of consent
Age of consent for heterosexual sex in various countries. Australia and the United States are federal states where the age of consent varies from federative unit to federative unit. Federal states in which all federative units adopt the same age of consent (e.g. Canada, Brazil, India, Mexico and Russia) are presented without internal federative divisions. 

  puberty   12   13   14   15   16   17   18
  must be married   no data available / other

Africa

Americas

Asia

Europe

Oceania

History and social attitudes

Traditional attitudes

In traditional societies, the age of consent for a sexual union was a matter for the family to decide, or a tribal custom. In most cases, this coincided with signs of puberty, menstruation for a woman, and pubic hair for a man.

Reliable data for ages at marriage is scarce. In England, for example, the only reliable data in the early modern period comes from property records made after death. Not only were the records relatively rare, but not all bothered to record the participants' ages, and it seems that the more complete the records are, the more likely they are to reveal young marriages. Modern historians have sometimes shown reluctance to accept evidence of young ages of marriage, dismissing it as a 'misreading' by a later copier of the records.

In the 12th century, Gratian, the influential compiler of canon law in medieval Europe, accepted the age of puberty for marriage (not sex) to be around twelve for girls and around fourteen for boys but acknowledged consent to be meaningful if both children were older than seven years of age. There were authorities that said that such consent for entering marriage could take place earlier. Marriage would then be valid as long as neither of the two parties annulled the marital agreement before reaching puberty, or if they had already consummated the marriage. Judges sometimes honored marriages based on mutual consent at ages younger than seven: in contrast to established canon, there are recorded marriages of two- and three-year-olds.

The first recorded age-of-consent law dates from 1275 in England; as part of its provisions on rape, the Statute of Westminster 1275 made it a misdemeanor to "ravish" a "maiden within age," whether with or without her consent. The phrase "within age" was later interpreted by jurist Sir Edward Coke (England, 17th century) as meaning the age of marriage, which at the time was twelve years of age.

The American colonies followed the English tradition, and the law was more of a guide. For example, Mary Hathaway (Virginia, 1689) was only nine when she was married to William Williams. Sir Edward Coke "made it clear that the marriage of girls under 12 was normal, and the age at which a girl who was a wife was eligible for a dower from her husband's estate was 9 even though her husband be only four years old."

In 17th-century Spain an official legal document of the central council of the Inquisition of Madrid (The Suprema) written in 1614 stated that "adults" were then considered to be "women over twelve and men over fourteen".

In the 16th century, a small number of Italian and German states set the minimum age for sexual intercourse for girls, setting it at twelve years. Towards the end of the 18th century, other European countries also began to enact similar laws. The first French Constitution of 1791 established the minimum age at eleven years. Portugal, Spain, Denmark and the Swiss cantons initially set the minimum age at ten to twelve years.

Age of consent laws were, historically, difficult to follow and enforce: legal norms based on age were not, in general, common until the 19th century, because clear proof of exact age and precise date of birth were often unavailable.

In Australia, 18th century thought was that children were inherently sinful and vulnerable to sexual temptations. Punishment for "giving in" to these temptations was generally left to parents and was not seen as a government matter, except in the case of rape. Australian children had few rights and were legally considered the chattel of their parents. From the late 18th century, and especially in the 19th century, attitudes started to change. By the mid-19th century there was increased concern over child sexual abuse.

Reforms in the 19th and 20th century

A general shift in social and legal attitudes toward issues of sex occurred during the modern era. Attitudes on the appropriate age of permission for females to engage in sexual activity drifted toward adulthood. While ages from ten to thirteen years were typically regarded as acceptable ages for sexual consent in Western countries during the mid-19th century, by the end of the 19th century changing attitudes towards sexuality and childhood resulted in the raising of the age of consent.

Several articles written by British investigative journalist William Thomas Stead in the late 19th century on the issue of child prostitution in London led to public outrage and ultimately to the raising of the age of consent to 16.

English common law had traditionally set the age of consent within the range of ten to twelve years old, but the Offences Against the Person Act 1875 raised this to thirteen in Great Britain and Ireland. Early feminists of the Social Purity movement, such as Josephine Butler and others, instrumental in securing the repeal of the Contagious Diseases Acts, began to turn towards the problem of child prostitution by the end of the 1870s. Sensational media revelations about the scourge of child prostitution in London in the 1880s then caused outrage among the respectable middle-classes, leading to pressure for the age of consent to be raised again.

The investigative journalist William Thomas Stead of the Pall Mall Gazette was pivotal in exposing the problem of child prostitution in the London underworld through a publicity stunt. In 1885 he "purchased" one victim, Eliza Armstrong, the thirteen-year-old daughter of a chimney sweep, for five pounds and took her to a brothel where she was drugged. He then published a series of four exposés entitled The Maiden Tribute of Modern Babylon, which shocked its readers with tales of child prostitution and the abduction, procurement, and sale of young English virgins to Continental "pleasure palaces". The "Maiden Tribute" was an instant sensation with the reading public, and Victorian society was thrown into an uproar about prostitution. Fearing riots on a national scale, the Home Secretary, Sir William Harcourt, pleaded in vain with Stead to cease publication of the articles. A wide variety of reform groups held protest meetings and marched together to Hyde Park demanding that the age of consent be raised. The government was forced to propose the Criminal Law Amendment Act 1885, which raised the age of consent from thirteen to sixteen and clamped down on prostitution.

In the United States, as late as the 1880s most states set the minimum age at ten to twelve (in Delaware, it was seven in 1895). Inspired by the "Maiden Tribute" articles, female reformers in the U.S. initiated their own campaign, which petitioned legislators to raise the legal minimum age to at least sixteen, with the ultimate goal to raise the age to eighteen. The campaign was successful, with almost all states raising the minimum age to sixteen to eighteen years by 1920.

In France, Portugal, Denmark, the Swiss cantons and other countries, the minimum age was raised to between thirteen and sixteen years in the following decades. Though the original arguments for raising the age of consent were based on morality, since then the raison d'être of the laws has changed to child welfare and a so-called right to childhood or innocence.

In France, under the Napoleonic Code, the age of consent was set in 1832 at eleven, and was raised to thirteen in 1863. It was increased to fifteen in 1945. In the 1970s, a group of prominent French intellectuals advocated for the repeal of the age of consent laws, but did not succeed.

In Spain, it was set in 1822 at "puberty age", and changed to twelve in 1870, which was kept until 1999, when it became 13; and in 2015 it was raised to 16.

21st century and present day situation

In the 21st century, concerns about child sex tourism and commercial sexual exploitation of children gained international prominence, and have resulted in legislative changes in several jurisdictions, as well as in the adoption of several international instruments.

The Council of Europe Convention on the Protection of Children against Sexual Exploitation and Sexual Abuse (Lanzarote, 25 October 2007), and the European Union's Directive 2011/92/EU of the European Parliament and of the Council of 13 December 2011 on combating the sexual abuse and sexual exploitation of children and child pornography were adopted.

The Optional Protocol on the Sale of Children, Child Prostitution and Child Pornography came into force in 2002.

The Protocol to Prevent, Suppress and Punish Trafficking in Persons, especially Women and Children, which came into force in 2003, prohibits commercial sexual exploitation of children.

The Council of Europe Convention on Action against Trafficking in Human Beings (which came into force in 2008) also deals with commercial sexual exploitation of children.

Several Western countries have raised their ages of consent recently. These include Canada (in 2008—from 14 to 16); and in Europe, Iceland (in 2007—from 14 to 15), Lithuania (in 2010—from 14 to 16), Croatia (in 2013—from 14 to 15), and Spain (in 2015—from 13 to 16).

The International Criminal Court Statute does not provide a specific age of consent in its rape/sexual violence statute, but makes reference to sexual acts committed against persons "incapable of giving genuine consent"; and the explicative footnote states, "It is understood that a person may be incapable of giving genuine consent if affected by natural, induced or age-related incapacity." (see note 51)

Law

Sexual relations with a person under the age of consent is a crime in most countries; Jurisdictions use a variety of terms for the offense, including child sexual abuse, statutory rape, illegal carnal knowledge, corruption of a minor, besides others.

The enforcement practices of age-of-consent laws vary depending on the social sensibilities of the particular culture (see above). Often, enforcement is not exercised to the letter of the law, with legal action being taken only when a sufficiently socially-unacceptable age gap exists between the two individuals, or if the perpetrator is in a position of power over the minor (e.g. a teacher, minister, or doctor). The sex of each participant can also influence perceptions of an individual's guilt and therefore enforcement.

Age

The threshold age for engaging in sexual activity varies between jurisdictions. Most jurisdictions have set a fixed age of consent. However, some jurisdictions permit sex with a person after the onset of their puberty, such as Yemen, but only in marriage. Ages can also vary based on the type of calendar used, such as the Lunar calendar, how birth dates in leap years are handled, or even the method by which birth date is calculated.

Defenses and exceptions

The age of consent is a legal barrier to the minor's ability to consent and therefore obtaining consent is not in general a defense to having sexual relations with a person under the prescribed age, for example:

Reasonable belief that the victim is over the age of consent
In some jurisdictions it is a defense if the accused can show that he or she reasonably believed the victim was over the age of consent. However, where such a defense is provided, it normally applies only when the victim is close to the age of consent or the accused can show due diligence in determining the age of the victim (e.g. an underage person who used a fake identification document claiming to be of legal age).
Marriage
In various jurisdictions, age of consent laws do not apply if the parties are legally married to each other.
Close-in-age exemptions
Similar age
Some jurisdictions have laws explicitly allowing sexual acts with minors under the age of consent if their partner is close in age to them. For instance, in Canada, the age of consent is 16, but there are three close-in-age exemptions: sex with minors aged 14–15 is permitted if the partner is less than five years older, and sex with minors aged 12–13 is permitted if the partner is less than two years older, and sex with minors aged 0–11 is permitted if the partner is 12 or 13 years of age. However, this exception also requires that the partner not be in a position of trust over the minor.
Age under threshold
Another approach takes the form of a stipulation that sexual intercourse between a minor and an older partner is legal under the condition that the latter does not exceed a certain age. For example, the age of consent in the US state of Delaware is 18, but it is allowed for teenagers aged 16 and 17 to engage in sexual intercourse as long as the older partner is younger than 30. The example above for sex with minors aged 0–11 with a partner younger than 14 in Canada also takes this form.
Similar maturity
Other countries state that the sexual conduct with the minor is not to be punished if the partners are of a similar age and development: for instance, the age of consent in Finland is 16, but the law states that the act will not be punished if "there is no great difference in the ages or the mental and physical maturity of the persons involved". In Slovenia, the age of consent is 15, but the activity is only deemed criminal if there is "a marked discrepancy between the maturity of the perpetrator and that of the victim".
Homosexual and heterosexual age discrepancies
Some jurisdictions, such as the Bahamas, UK overseas territory of the Cayman Islands, Chile, Paraguay and Suriname have a higher age of consent for same-sex sexual activity. However, such discrepancies are increasingly being challenged. Within Bermuda for example (since 1 November 2019 under section 177 of the Criminal Code Act 1907) the age of consent for vaginal and oral sex is 16, but for anal sex it is 18. In Canada, the United Kingdom and Western Australia, for example, the age of consent was formerly 21 for same-sex sexual activity between males (with no laws regarding lesbian sexual activities), while it was 16 for heterosexual sexual activity; this is no longer the case and the age of consent for all sexual activity is 16. In June 2019, the Canadian Government repealed the section of the Criminal Code that set a higher age of consent for anal intercourse.
Gender-age differentials
In some jurisdictions (such as Indonesia), there are different ages of consent for heterosexual sexual activity that are based on the gender of each person. In countries where there are gender-age differentials, the age of consent may be higher for girls—for example in Papua New Guinea, where the age of consent for heterosexual sex is 16 for girls and 14 for boys, or they may be higher for males, such as in Indonesia, where males must be 19 years old and females must be 16 years old. There are also numerous jurisdictions—such as Kuwait and the Palestinian Territories—in which marriage laws govern the gender-age differential. In these jurisdictions, it is illegal to have sexual intercourse outside of marriage, so the de facto age of consent is the marriageable age. In Kuwait, this means that boys must be at least 17 and girls at least 15 years old.
Position of authority/trust
In most jurisdictions where the age of consent is below 18 (such as England and Wales), in cases where a person aged 18 or older is in a position of trust over a person under 18, the age of consent usually rises to 18 or higher. Examples of such positions of trust include relationships between teachers and students. For example, in England and Wales the age of consent is 16, but if the person is a student of the older person it becomes 18.
Circumstances of the relationship
In several jurisdictions, it is illegal to engage in sexual activity with a person under a certain age under certain circumstances regarding the relationship in question, such as if it involves taking advantage of or corrupting the morals of the young person. For example, while the age of consent is 14 in Germany and 16 in Canada, it is illegal in both countries to engage in sexual activity with a person under 18 if the activity exploits the younger person. Another example is in Mexico, where there is a crime called "estupro" defined as sexual activity with a person over the age of consent but under a certain age limit (generally 18) in which consent of the younger person was obtained through seduction and/or deceit. In Pennsylvania, the age of consent is officially 16, but if the older partner is 18 or older, he/she may still be prosecuted for corruption of minors if he/she corrupts or tends to corrupt the morals of the younger person.

Extraterritoriality

A growing number of countries have specific extraterritorial legislation that prosecutes their citizens in their homeland should they engage in illicit sexual conduct in a foreign country with children. In 2008, ECPAT reported that 44 countries had extraterritorial child sex legislation. For example, PROTECT Act of 2003, a federal United States law bans sexual activity by its citizens with foreigners or with U.S. citizens from another state, if the partner is under 18 and the activity is illegal under the federal, state, or local law. This applies in cases where any of the partners travels into or out of the United States, or from one state into another, for the purpose of an illegal sexual encounter.

Other issues

Gender of participants

There is debate as to whether the gender of those involved should lead to different treatment of the sexual encounter, in law or in practice. Traditionally, age of consent laws regarding vaginal intercourse were often meant to protect the chastity of unmarried girls. Many feminists and social campaigners in the 1970s have objected to the social importance of virginity, and have also attempted to change the stereotypes of female passivity and male aggression; demanding that the law protect children from exploitation regardless of their gender, rather than dealing with concerns of chastity. This has led to gender-neutral laws in many jurisdictions. On the other hand, there is an opposing view which argues that the act of vaginal intercourse is an "unequal act" for males and females, due to issues such as pregnancy, increased risk of STDs, and risk of physical injury if the girl is too young and not physically ready. In the US, in Michael M. v. Superior Ct.450 U.S. 464 (1981) it was ruled that the double standard of offering more legal protection to girls is valid because "the Equal Protection Clause does not mean that the physiological differences between men and women must be disregarded".

Traditionally, many age of consent laws dealt primarily with men engaging in sexual acts with underage girls and boys (the latter acts often falling under sodomy and buggery laws). This means that in some legal systems, issues of women having sexual contact with underage partners were rarely acknowledged. For example, until 2000, in the UK, before the Sexual Offences (Amendment) Act 2000, there was no statutory age of consent for lesbian sex. In New Zealand, before 2005, there were no age of consent laws dealing with women having sex with underage boys. Previously, in Fiji, male offenders of child sexual abuse could receive up to life imprisonment, whilst female offenders would receive up to seven years. Situations like these have been attributed to societal views on traditional gender roles, and to constructs of male sexuality and female sexuality; according to E Martellozzo, "[V]iewing females as perpetrators of sexual abuse goes against every stereotype that society has of women: women as mothers and caregivers and not as people who abuse and harm". Alissa Nutting argues that women are not acknowledged as perpetrators of sex crimes because society does not accept that women have an autonomous sexuality of their own.

Marriage and the age of consent

The age at which a person can be legally married can differ from the age of consent. In jurisdictions where the marriageable age is lower than the age of consent, those laws usually override the age of consent laws in the case of a married couple where one or both partners are below the age of consent. Some jurisdictions prohibit all sex outside of marriage irrespective of age, as in the case of Yemen.

Prostitution

In many countries, there are specific laws dealing with child prostitution.

Pornography and "jailbait" images

In some countries, states, or other jurisdictions, the age of consent may be lower than the age at which a person can appear in pornographic images and films. In many jurisdictions, the minimum age for participation and even viewing such material is 18. As such, in some jurisdictions, films and images showing individuals under the age of 18, but above the age of consent, that meet the legal definition of child pornography are prohibited despite the fact that the sexual acts depicted are legal to engage in otherwise under that jurisdiction's age of consent laws. In those cases, it is only the filming of the sex act that is the crime as the act itself would not be considered a sex crime. For example, in the United States under federal law it is a crime to film minors below 18 in sexual acts, even in states where the age of consent is below 18. In those states, charges such as child pornography can be used to prosecute someone having sex with a minor, who could not otherwise be prosecuted for statutory rape, provided they filmed or photographed the act.

Jailbait images can be differentiated from child pornography, as they do not feature minors before the onset of puberty, nor do they contain nudity. The images are, however, usually sexualized, often featuring tween or young teenagers in bikinis, skirts, underwear or lingerie. Whether or not these images are legal is debated. When questioned regarding their legality legal analyst Jeffrey Toobin stated he thought it was not illegal, though legal expert Sunny Hostin was more skeptical, describing jailbait images as "borderline" child pornography which may be illegal.

Health

The human immune system continues to develop after puberty. The age of exposure has an influence upon if the immune system can fend off infections in general, and this is also true in the case of some sexually transmitted diseases. For example, a risk factor for HPV strains causing genital warts is sexual debut at a young age; if this extends to the cancer causing strains, then sexual debut at a young age would potentially also increase risk of persistence of HPV infections that cause the very HPV induced cancers that are being diagnosed in spiking numbers of relatively young people.

Initiatives to change the age of consent

Age-of-consent reform refers to the efforts of some individuals or groups, for different reasons, to alter or abolish age-of-consent laws. These efforts advocate positions such as:

  • Introductions of close-in-age exceptions.
  • Reducing the age-of-consent for homosexual activity to that of heterosexual activity.
  • A change in the way that age-of-consent laws are examined in court.
  • Either increases in the ages of consent or more severe penalties or both.
  • Either decreases in the ages of consent or less severe penalties or both.
  • Abolition of the age-of-consent laws either permanently or as a temporary, practical expedient.

Class (computer programming)

From Wikipedia, the free encyclopedia

In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods). In many languages, the class name is used as the name for the class (the template itself), the name for the default constructor of the class (a subroutine that creates objects), and as the type of objects generated by instantiating the class; these distinct concepts are easily conflated. Although, to the point of conflation, one could argue that is a feature inherent in a language because of its polymorphic nature and why these languages are so powerful, dynamic and adaptable for use compared to languages without polymorphism present. Thus they can model dynamic systems (i.e. the real world, machine learning, AI) more easily.

When an object is created by a constructor of the class, the resulting object is called an instance of the class, and the member variables specific to the object are called instance variables, to contrast with the class variables shared across the class.

In some languages, classes are only a compile-time feature (new classes cannot be declared at run-time), while in other languages classes are first-class citizens, and are generally themselves objects (typically of type Class or similar). In these languages, a class that creates classes is called a metaclass.

Class vs. type

In casual use, people often refer to the "class" of an object, but narrowly speaking objects have type: the interface, namely the types of member variables, the signatures of member functions (methods), and properties these satisfy. At the same time, a class has an implementation (specifically the implementation of the methods), and can create objects of a given type, with a given implementation. In the terms of type theory, a class is an implementation‍—‌a concrete data structure and collection of subroutines‍—‌while a type is an interface. Different (concrete) classes can produce objects of the same (abstract) type (depending on type system); for example, the type Stack might be implemented with two classes – SmallStack (fast for small stacks, but scales poorly) and ScalableStack (scales well but high overhead for small stacks). Similarly, a given class may have several different constructors.

Class types generally represent nouns, such as a person, place or thing, or something nominalized, and a class represents an implementation of these. For example, a Banana type might represent the properties and functionality of bananas in general, while the ABCBanana and XYZBanana classes would represent ways of producing bananas (say, banana suppliers or data structures and functions to represent and draw bananas in a video game). The ABCBanana class could then produce particular bananas: instances of the ABCBanana class would be objects of type Banana. Often only a single implementation of a type is given, in which case the class name is often identical with the type name.

Design and implementation

Classes are composed from structural and behavioral constituents. Programming languages that include classes as a programming construct offer support, for various class-related features, and the syntax required to use these features varies greatly from one programming language to another.

Structure

UML notation for classes

A class contains data field descriptions (or properties, fields, data members, or attributes). These are usually field types and names that will be associated with state variables at program run time; these state variables either belong to the class or specific instances of the class. In most languages, the structure defined by the class determines the layout of the memory used by its instances. Other implementations are possible: for example, objects in Python use associative key-value containers.

Some programming languages such as Eiffel support specification of invariants as part of the definition of the class, and enforce them through the type system. Encapsulation of state is necessary for being able to enforce the invariants of the class.

Behavior

The behavior of class or its instances is defined using methods. Methods are subroutines with the ability to operate on objects or classes. These operations may alter the state of an object or simply provide ways of accessing it. Many kinds of methods exist, but support for them varies across languages. Some types of methods are created and called by programmer code, while other special methods—such as constructors, destructors, and conversion operators—are created and called by compiler-generated code. A language may also allow the programmer to define and call these special methods.

The concept of class interface

Every class implements (or realizes) an interface by providing structure and behavior. Structure consists of data and state, and behavior consists of code that specifies how methods are implemented. There is a distinction between the definition of an interface and the implementation of that interface; however, this line is blurred in many programming languages because class declarations both define and implement an interface. Some languages, however, provide features that separate interface and implementation. For example, an abstract class can define an interface without providing implementation.

Languages that support class inheritance also allow classes to inherit interfaces from the classes that they are derived from.

For example, if "class A" inherits from "class B" and if "class B" implements the interface "interface B" then "class A" also inherits the functionality(constants and methods declaration) provided by "interface B".

In languages that support access specifiers, the interface of a class is considered to be the set of public members of the class, including both methods and attributes (via implicit getter and setter methods); any private members or internal data structures are not intended to be depended on by external code and thus are not part of the interface.

Object-oriented programming methodology dictates that the operations of any interface of a class are to be independent of each other. It results in a layered design where clients of an interface use the methods declared in the interface. An interface places no requirements for clients to invoke the operations of one interface in any particular order. This approach has the benefit that client code can assume that the operations of an interface are available for use whenever the client has access to the object.

Example

The buttons on the front of your television set are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to toggle the television on and off. In this example, your particular television is the instance, each method is represented by a button, and all the buttons together compose the interface (other television sets that are the same model as yours would have the same interface). In its most common form, an interface is a specification of a group of related methods without any associated implementation of the methods.

A television set also has a myriad of attributes, such as size and whether it supports colour, which together comprise its structure. A class represents the full description of a television, including its attributes (structure) and buttons (interface).

Getting the total number of televisions manufactured could be a static method of the television class. This method is clearly associated with the class, yet is outside the domain of each individual instance of the class. A static method that finds a particular instance out of the set of all television objects is another example.

Member accessibility

The following is a common set of access specifiers:

  • Private (or class-private) restricts the access to the class itself. Only methods that are part of the same class can access private members.
  • Protected (or class-protected) allows the class itself and all its subclasses to access the member.
  • Public means that any code can access the member by its name.

Although many object-oriented languages support the above access specifiers, their semantics may differ.

Object-oriented design uses the access specifiers in conjunction with careful design of public method implementations to enforce class invariants—constraints on the state of the objects. A common usage of access specifiers is to separate the internal data of a class from its interface: the internal structure is made private, while public accessor methods can be used to inspect or alter such private data.

Access specifiers do not necessarily control visibility, in that even private members may be visible to client external code. In some languages, an inaccessible but visible member may be referred to at run-time (for example, by a pointer returned from a member function), but an attempt to use it by referring to the name of the member from client code will be prevented by the type checker.

The various object-oriented programming languages enforce member accessibility and visibility to various degrees, and depending on the language's type system and compilation policies, enforced at either compile-time or run-time. For example, the Java language does not allow client code that accesses the private data of a class to compile. In the C++ language, private methods are visible, but not accessible in the interface; however, they may be made invisible by explicitly declaring fully abstract classes that represent the interfaces of the class.

Some languages feature other accessibility schemes:

  • Instance vs. class accessibility: Ruby supports instance-private and instance-protected access specifiers in lieu of class-private and class-protected, respectively. They differ in that they restrict access based on the instance itself, rather than the instance's class.
  • Friend: C++ supports a mechanism where a function explicitly declared as a friend function of the class may access the members designated as private or protected.
  • Path-based: Java supports restricting access to a member within a Java package, which is the logical path of the file. However, it is a common practice when extending a Java framework to implement classes in the same package as a framework class in order to access protected members. The source file may exist in a completely different location, and may be deployed to a different .jar file, yet still be in the same logical path as far as the JVM is concerned.

Inter-class relationships

In addition to the design of standalone classes, programming languages may support more advanced class design based upon relationships between classes. The inter-class relationship design capabilities commonly provided are compositional and hierarchical.

Compositional

Classes can be composed of other classes, thereby establishing a compositional relationship between the enclosing class and its embedded classes. Compositional relationship between classes is also commonly known as a has-a relationship. For example, a class "Car" could be composed of and contain a class "Engine". Therefore, a Car has an Engine. One aspect of composition is containment, which is the enclosure of component instances by the instance that has them. If an enclosing object contains component instances by value, the components and their enclosing object have a similar lifetime. If the components are contained by reference, they may not have a similar lifetime. For example, in Objective-C 2.0:

@interface Car : NSObject

@property NSString *name;
@property Engine *engine
@property NSArray *tires;

@end

This Car class has an instance of NSString (a string object), Engine, and NSArray (an array object).

Hierarchical

Classes can be derived from one or more existing classes, thereby establishing a hierarchical relationship between the derived-from classes (base classes, parent classes or superclasses) and the derived class (child class or subclass) . The relationship of the derived class to the derived-from classes is commonly known as an is-a relationship. For example, a class 'Button' could be derived from a class 'Control'. Therefore, a Button is a Control. Structural and behavioral members of the parent classes are inherited by the child class. Derived classes can define additional structural members (data fields) and behavioral members (methods) in addition to those that they inherit and are therefore specializations of their superclasses. Also, derived classes can override inherited methods if the language allows.

Not all languages support multiple inheritance. For example, Java allows a class to implement multiple interfaces, but only inherit from one class. If multiple inheritance is allowed, the hierarchy is a directed acyclic graph (or DAG for short), otherwise it is a tree. The hierarchy has classes as nodes and inheritance relationships as links. Classes in the same level are more likely to be associated than classes in different levels. The levels of this hierarchy are called layers or levels of abstraction.

Example (Simplified Objective-C 2.0 code, from iPhone SDK):

@interface UIResponder : NSObject //...
@interface UIView : UIResponder //...
@interface UIScrollView : UIView //...
@interface UITableView : UIScrollView //...

In this example, a UITableView is a UIScrollView is a UIView is a UIResponder is an NSObject.

Definitions of subclass

Conceptually, a superclass is a superset of its subclasses. For example, a common class hierarchy would involve GraphicObject as a superclass of Rectangle and Ellipse, while Square would be a subclass of Rectangle. These are all subset relations in set theory as well, i.e., all squares are rectangles but not all rectangles are squares.

A common conceptual error is to mistake a part of relation with a subclass. For example, a car and truck are both kinds of vehicles and it would be appropriate to model them as subclasses of a vehicle class. However, it would be an error to model the component parts of the car as subclass relations. For example, a car is composed of an engine and body, but it would not be appropriate to model engine or body as a subclass of car.

In object-oriented modeling these kinds of relations are typically modeled as object properties. In this example, the Car class would have a property called parts. parts would be typed to hold a collection of objects, such as instances of Body, Engine, Tires, etc. Object modeling languages such as UML include capabilities to model various aspects of "part of" and other kinds of relations – data such as the cardinality of the objects, constraints on input and output values, etc. This information can be utilized by developer tools to generate additional code beside the basic data definitions for the objects, such as error checking on get and set methods.

One important question when modeling and implementing a system of object classes is whether a class can have one or more superclasses. In the real world with actual sets it would be rare to find sets that didn't intersect with more than one other set. However, while some systems such as Flavors and CLOS provide a capability for more than one parent to do so at run time introduces complexity that many in the object-oriented community consider antithetical to the goals of using object classes in the first place. Understanding which class will be responsible for handling a message can get complex when dealing with more than one superclass. If used carelessly this feature can introduce some of the same system complexity and ambiguity classes were designed to avoid.

Most modern object-oriented languages such as Smalltalk and Java require single inheritance at run time. For these languages, multiple inheritance may be useful for modeling but not for an implementation.

However, semantic web application objects do have multiple superclasses. The volatility of the Internet requires this level of flexibility and the technology standards such as the Web Ontology Language (OWL) are designed to support it.

A similar issue is whether or not the class hierarchy can be modified at run time. Languages such as Flavors, CLOS, and Smalltalk all support this feature as part of their meta-object protocols. Since classes are themselves first-class objects, it is possible to have them dynamically alter their structure by sending them the appropriate messages. Other languages that focus more on strong typing such as Java and C++ do not allow the class hierarchy to be modified at run time. Semantic web objects have the capability for run time changes to classes. The rational is similar to the justification for allowing multiple superclasses, that the Internet is so dynamic and flexible that dynamic changes to the hierarchy are required to manage this volatility.

Orthogonality of the class concept and inheritance

Although class-based languages are commonly assumed to support inheritance, inheritance is not an intrinsic aspect of the concept of classes. Some languages, often referred to as "object-based languages", support classes yet do not support inheritance. Examples of object-based languages include earlier versions of Visual Basic.

Within object-oriented analysis

In object-oriented analysis and in UML, an association between two classes represents a collaboration between the classes or their corresponding instances. Associations have direction; for example, a bi-directional association between two classes indicates that both of the classes are aware of their relationship. Associations may be labeled according to their name or purpose.

An association role is given end of an association and describes the role of the corresponding class. For example, a "subscriber" role describes the way instances of the class "Person" participate in a "subscribes-to" association with the class "Magazine". Also, a "Magazine" has the "subscribed magazine" role in the same association. Association role multiplicity describes how many instances correspond to each instance of the other class of the association. Common multiplicities are "0..1", "1..1", "1..*" and "0..*", where the "*" specifies any number of instances.

Taxonomy of classes

There are many categories of classes, some of which overlap.

Abstract and concrete

In a language that supports inheritance, an abstract class, or abstract base class (ABC), is a class that cannot be instantiated because it is either labeled as abstract or it simply specifies abstract methods (or virtual methods). An abstract class may provide implementations of some methods, and may also specify virtual methods via signatures that are to be implemented by direct or indirect descendants of the abstract class. Before a class derived from an abstract class can be instantiated, all abstract methods of its parent classes must be implemented by some class in the derivation chain.

Most object-oriented programming languages allow the programmer to specify which classes are considered abstract and will not allow these to be instantiated. For example, in Java, C# and PHP, the keyword abstract is used. In C++, an abstract class is a class having at least one abstract method given by the appropriate syntax in that language (a pure virtual function in C++ parlance).

A class consisting of only virtual methods is called a Pure Abstract Base Class (or Pure ABC) in C++ and is also known as an interface by users of the language. Other languages, notably Java and C#, support a variant of abstract classes called an interface via a keyword in the language. In these languages, multiple inheritance is not allowed, but a class can implement multiple interfaces. Such a class can only contain abstract publicly accessible methods.

A concrete class is a class that can be instantiated, as opposed to abstract classes, which cannot.

Local and inner

In some languages, classes can be declared in scopes other than the global scope. There are various types of such classes.

An inner class is a class defined within another class. The relationship between an inner class and its containing class can also be treated as another type of class association. An inner class is typically neither associated with instances of the enclosing class nor instantiated along with its enclosing class. Depending on language, it may or may not be possible to refer to the class from outside the enclosing class. A related concept is inner types, also known as inner data type or nested type, which is a generalization of the concept of inner classes. C++ is an example of a language that supports both inner classes and inner types (via typedef declarations).

Another type is a local class, which is a class defined within a procedure or function. This limits references to the class name to within the scope where the class is declared. Depending on the semantic rules of the language, there may be additional restrictions on local classes compared to non-local ones. One common restriction is to disallow local class methods to access local variables of the enclosing function. For example, in C++, a local class may refer to static variables declared within its enclosing function, but may not access the function's automatic variables.

Metaclasses

Metaclasses are classes whose instances are classes. A metaclass describes a common structure of a collection of classes and can implement a design pattern or describe particular kinds of classes. Metaclasses are often used to describe frameworks.

In some languages, such as Python, Ruby or Smalltalk, a class is also an object; thus each class is an instance of a unique metaclass that is built into the language. The Common Lisp Object System (CLOS) provides metaobject protocols (MOPs) to implement those classes and metaclasses. 

Non-subclassable

Non-subclassable classes allow programmers to design classes and hierarchies of classes where at some level in the hierarchy, further derivation is prohibited (a stand-alone class may be also designated as non-subclassable, preventing the formation of any hierarchy). Contrast this to abstract classes, which imply, encourage, and require derivation in order to be used at all. A non-subclassable class is implicitly concrete.

A non-subclassable class is created by declaring the class as sealed in C# or as final in Java or PHP. For example, Java's String class is designated as final.

Non-subclassable classes may allow a compiler (in compiled languages) to perform optimizations that are not available for subclassable classes. 

Open Class

An open class is one that can be changed. Typically, an executable program cannot be changed by customers. Developers can often change some classes, but typically cannot change standard or built-in ones. In Ruby, all classes are open. In Python, classes can be created at runtime, and all can be modified afterwards. Objective-C categories permit the programmer to add methods to an existing class without the need to recompile that class or even have access to its source code.

Mixins

Some languages have special support for mixins, though in any language with multiple inheritance a mixin is simply a class that does not represent an is-a-type-of relationship. Mixins are typically used to add the same methods to multiple classes; for example, a class UnicodeConversionMixin might provide a method called unicode_to_ascii when included in classes FileReader and WebPageScraper that do not share a common parent.

Partial

In languages supporting the feature, a partial class is a class whose definition may be split into multiple pieces, within a single source-code file or across multiple files. The pieces are merged at compile-time, making compiler output the same as for a non-partial class.

The primary motivation for introduction of partial classes is to facilitate the implementation of code generators, such as visual designers. It is otherwise a challenge or compromise to develop code generators that can manage the generated code when it is interleaved within developer-written code. Using partial classes, a code generator can process a separate file or coarse-grained partial class within a file, and is thus alleviated from intricately interjecting generated code via extensive parsing, increasing compiler efficiency and eliminating the potential risk of corrupting developer code. In a simple implementation of partial classes, the compiler can perform a phase of precompilation where it "unifies" all the parts of a partial class. Then, compilation can proceed as usual.

Other benefits and effects of the partial class feature include:

  • Enables separation of a class's interface and implementation code in a unique way.
  • Eases navigation through large classes within an editor.
  • Enables separation of concerns, in a way similar to aspect-oriented programming but without using any extra tools.
  • Enables multiple developers to work on a single class concurrently without the need to merge individual code into one file at a later time.

Partial classes have existed in Smalltalk under the name of Class Extensions for considerable time. With the arrival of the .NET framework 2, Microsoft introduced partial classes, supported in both C# 2.0 and Visual Basic 2005. WinRT also supports partial classes.

Example in VB.NET

This simple example, written in Visual Basic .NET, shows how parts of the same class are defined in two different files.

file1.vb

Partial Class MyClass
    Private _name As String
End Class
file2.vb

Partial Class MyClass
    Public Readonly Property Name() As String
         Get
             Return _name
         End Get
    End Property
End Class

When compiled, the result is the same as if the two files were written as one, like this:

Class MyClass
    Private _name As String
    Public Readonly Property Name() As String
         Get
             Return _name
         End Get
    End Property
End Class

Example in Objective-C

In Objective-C, partial classes, also known as categories, may even spread over multiple libraries and executables, like the following example. But a key difference is that Objective-C's categories can overwrite definitions in another interface declaration, and that categories aren't equal to original class definition (the first requires the last). Instead, .NET partial class can't have conflicting definitions, and all partial definitions are equal to the others.

In Foundation, header file NSData.h:

@interface NSData : NSObject

- (id)initWithContentsOfURL:(NSURL *)URL;
//...

@end

In user-supplied library, a separate binary from Foundation framework, header file NSData+base64.h:

#import <Foundation/Foundation.h>

@interface NSData (base64)

- (NSString *)base64String;
- (id)initWithBase64String:(NSString *)base64String;

@end

And in an app, yet another separate binary file, source code file main.m:

#import <Foundation/Foundation.h>
#import "NSData+base64.h"

int main(int argc, char *argv[])
{
    if (argc < 2)
        return EXIT_FAILURE;
    NSString *sourceURLString = [NSString stringWithCString:argv[1]];
    NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:sourceURLString]];
    NSLog(@"%@", [data base64String]);
    return EXIT_SUCCESS;
}

The dispatcher will find both methods called over the NSData instance and invoke both of them correctly.

Uninstantiable

Uninstantiable classes allow programmers to group together per-class fields and methods that are accessible at runtime without an instance of the class. Indeed, instantiation is prohibited for this kind of class.

For example, in C#, a class marked "static" can not be instantiated, can only have static members (fields, methods, other), may not have instance constructors, and is sealed

Unnamed

An unnamed class or anonymous class is a class that is not bound to a name or identifier upon definition. This is analogous to named versus unnamed functions.

Benefits

The benefits of organizing software into object classes fall into three categories:

  • Rapid development
  • Ease of maintenance
  • Reuse of code and designs

Object classes facilitate rapid development because they lessen the semantic gap between the code and the users. System analysts can talk to both developers and users using essentially the same vocabulary, talking about accounts, customers, bills, etc. Object classes often facilitate rapid development because most object-oriented environments come with powerful debugging and testing tools. Instances of classes can be inspected at run time to verify that the system is performing as expected. Also, rather than get dumps of core memory, most object-oriented environments have interpreted debugging capabilities so that the developer can analyze exactly where in the program the error occurred and can see which methods were called to which arguments and with what arguments.

Object classes facilitate ease of maintenance via encapsulation. When developers need to change the behavior of an object they can localize the change to just that object and its component parts. This reduces the potential for unwanted side effects from maintenance enhancements.

Software re-use is also a major benefit of using Object classes. Classes facilitate re-use via inheritance and interfaces. When a new behavior is required it can often be achieved by creating a new class and having that class inherit the default behaviors and data of its superclass and then tailor some aspect of the behavior or data accordingly. Re-use via interfaces (also known as methods) occurs when another object wants to invoke (rather than create a new kind of) some object class. This method for re-use removes many of the common errors that can make their way into software when one program re-uses code from another.

Run-time representation

As a data type, a class is usually considered as a compile-time construct. A language or library may also support prototype or factory metaobjects that represent run-time information about classes, or even represent metadata that provides access to reflection facilities and ability to manipulate data structure formats at run-time. Many languages distinguish this kind of run-time type information about classes from a class on the basis that the information is not needed at run-time. Some dynamic languages do not make strict distinctions between run-time and compile-time constructs, and therefore may not distinguish between metaobjects and classes.

For example, if Human is a metaobject representing the class Person, then instances of class Person can be created by using the facilities of the Human metaobject.

Political psychology

From Wikipedia, the free encyclopedia ...