HOME

TheInfoList




In
object-oriented programming Object-oriented programming (OOP) is a programming paradigm Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. Some paradigms are concerned mai ...
, a class is an extensible program-code-template for creating
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Entity, something that is tangible and within the grasp of the senses ** Object (abstract), an object which does not exist at any particular time or pl ...
s, providing initial values for state (
member variable In object-oriented programming Object-oriented programming (OOP) is a programming paradigm Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. S ...
s) 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 In computer programming Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a particular task. Programming involves tasks such as analysis, generat ...
that creates objects), and as the
type Type may refer to: Science and technology Computing * Typing, producing text via a keyboard, typewriter, etc. * Data type, collection of values used for computations. * File type * TYPE (DOS command), a command to display contents of a file. * 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 variable In object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "Object (computer science), objects", which can contain data and code: data in the form of Field (computer science), fields (oft ...
s, to contrast with the
class variableIn object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "Object (computer science), objects", which can contain data and code: data in the form of Field (computer science), fields (often ...
s 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 citizen In programming language design, a first-class citizen (also type, object, entity, or value) in a given programming language A programming language is a formal language comprising a Instruction set architecture, set of instructions that produce ...
s, and are generally themselves objects (typically of type or similar). In these languages, a class that creates classes is called a
metaclass In object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "Object (computer science), objects", which can contain data and code: data in the form of Field (computer science), fields (oft ...
.


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 function A method in object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "Object (computer science), objects", which can contain data and code: data in the form of Field (computer science), fi ...
s (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 implementationa ''concrete''
data structure In computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of ...

data structure
and collection of subroutineswhile a type is an
interface Interface or interfacing may refer to: Academic journals * Interface (journal), ''Interface'' (journal), by the Electrochemical Society * ''Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Lin ...
. Different (concrete) classes can produce objects of the same (abstract) type (depending on type system); for example, the type might be implemented with two classes (fast for small stacks, but scales poorly) and (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 type might represent the properties and functionality of
banana A banana is an elongated, edible fruit In botany Botany, also called , plant biology or phytology, is the science of plant life and a branch of biology. A botanist, plant scientist or phytologist is a scientist who specia ...

banana
s in general, while the and 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 class could then produce particular bananas: instances of the class would be objects of type . 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

A class contains
data Data (; ) are individual facts A fact is something that is truth, true. The usual test for a statement of fact is verifiability—that is whether it can be demonstrated to correspond to experience. Standard reference works are often used ...
field Field may refer to: Expanses of open ground * Field (agriculture), an area of land used for agricultural purposes * Airfield, an aerodrome that lacks the infrastructure of an airport * Battlefield * Lawn, an area of mowed grass * Meadow, a grassl ...
descriptions (or ''
properties Property (''latin: Res Privata'') in the abstract is what belongs to or with something, whether as an attribute or as a component of said thing. In the context of this article, it is one or more components (rather than attributes), whether phys ...
'', ''
fields File:A NASA Delta IV Heavy rocket launches the Parker Solar Probe (29097299447).jpg, FIELDS heads into space in August 2018 as part of the ''Parker Solar Probe'' FIELDS is a science instrument on the ''Parker Solar Probe'' (PSP), designed to mea ...
'', ''data
members Member may refer to: * Military jury, referred to as "Members" in military jargon * Element (mathematics), an object that belongs to a mathematical set * In object-oriented programming, a member of a class ** Field (computer science), entries in ...
'', or ''
attributes Attribute may refer to: * Attribute (philosophy) In logic Logic (from Ancient Greek, Greek: grc, wikt:λογική, λογική, label=none, lit=possessed of reason, intellectual, dialectical, argumentative, translit=logikḗ)Also relate ...
''). 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 PYTHON was a Cold War contingency plan of the Government of the United Kingdom, British Government for the continuity of government in the event of Nuclear warfare, nuclear war. Background Following the report of the Strath Committee in 1955, the ...
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 Encapsulation may refer to: Chemistry * Molecular encapsulation, in chemistry, the confinement of an individual molecule within a larger molecule * Micro-encapsulation, in material science, the coating of microscopic particles with another materi ...
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
subroutine In computer programming Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a particular task. Programming involves tasks such as analysis, generat ...
s 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 A structure is an arrangement and organization of interrelated elements in a material object or system A system is a group of Interaction, interacting or interrelated elements that act according to a set of rules to form a unified whole. ...
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 In programming languages, an abstract type is a type in a nominative type system that cannot be Instance (computer science), instantiated directly; a type that is not abstract – which ''can'' be instantiated – is called a ''concrete type''. Ev ...
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 Access modifiers (or access specifiers) are keywords in object-oriented language Object-oriented programming (OOP) is a programming paradigm based on the concept of "Object (computer science), objects", which can contain data and code: da ...
, 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 Access modifiers (or access specifiers) are keywords in object-oriented language Object-oriented programming (OOP) is a programming paradigm based on the concept of "Object (computer science), objects", which can contain data and code: da ...
: * ''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 methodIn computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of Algorith ...
s 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 In programming language A programming language is a formal language In mathematics Mathematics (from Ancient Greek, Greek: ) includes the study of such topics as quantity (number theory), mathematical structure, structure (algebra) ...
and compilation policies, enforced at either
compile-time In computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of Algo ...
or run-time. For example, the
Java Java ( id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 147.7 million people, Java is the world's List of ...
language does not allow client code that accesses the private data of a class to compile. In the
C++ C++ () is a general-purpose programming language In computer software, a general-purpose programming language is a programming language dedicated to a general-purpose, designed to be used for writing software in a wide variety of application ...

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 A ruby is a pink-ish red to blood-red colored gemstone A gemstone (also called a fine gem, jewel, precious stone, or semi-precious stone) is a piece of mineral In geology and mineralogy, a mineral or mineral species is, broadly spea ...
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 functionIn object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "Object (computer science), objects", which can contain data and code: data in the form of Field (computer science), fields (often ...
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 A Java package organizes Java Java ( id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands The Greater Sunda Islands are four tropical islands situated within Southeast Asia, in the Pacific Ocean. The islands, Borneo, Java, Sula ...
, 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 In database designDatabase design is the organization of data according to a database model. The designer determines what data must be stored and how the data elements interrelate. With this information, they can begin to fit the data to the databa ...
'' 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 class ''has'' an instance of (a
string String or strings may refer to: *String (structure), a long flexible structure made from threads twisted together, which is used to tie, bind, or hang other objects Arts, entertainment, and media Films * Strings (1991 film), ''Strings'' (1991 fil ...
object), , and (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 ') 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 In knowledge representation Knowledge representation and reasoning (KR², KR&R) is the field of artificial intelligence Artificial intelligence (AI) is intelligence demonstrated by machines, unlike the natural intelligence human intelligence ...
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 In mathematics Mathematics (from Greek: ) includes the study of such topics as numbers (arithmetic and number theory), formulas and related structures (algebra), shapes and spaces in which they are contained (geometry), and quantities and ...

directed acyclic graph
(or DAG for short), otherwise it is a
tree In botany, a tree is a perennial plant with an elongated Plant stem, stem, or trunk (botany), trunk, supporting branches and leaves in most species. In some usages, the definition of a tree may be narrower, including only wood plants with se ...
. The hierarchy has classes as nodes and inheritance relationships as links. Classes in the same level are more likely to be
associatedAssociated may refer to: *Associated, former name of Avon, Contra Costa County, California *Associated Hebrew Schools of Toronto, a school in Canada *Associated Newspapers, former name of DMG Media, a British publishing company See also

*Associ ...
than classes in different levels. The levels of this hierarchy are called
layers Layer or layered may refer to: Arts, entertainment, and media Music Albums * ''Layers'' (Kungs album) * ''Layers'' (Les McCann album) * ''Layers'' (Royce da 5'9" album) Songs *"Layers", the title track of Royce da 5'9"'s sixth studio album Othe ...
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 In mathematics Mathematics (from Ancient Greek, Greek: ) includes the study of such topics as quantity (number theory), mathematical structure, structure (algebra), space (geometry), and calculus, change (mathematical analysis, analysis). ...
of its subclasses. For example, a common class hierarchy would involve as a superclass of and , while would be a subclass of . These are all 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 Object-oriented modeling (OOM) is an approach to modeling an application that is used at the beginning of the software life cycle when using an object-oriented approach to software development. The software life cycle is typically divided up into ...
these kinds of relations are typically modeled as object properties. In this example, the class would have a property called . would be typed to hold a collection of objects, such as instances of , , , etc. Object modeling languages such as
UML UML may refer to: * Unified Modeling Language, a software modeling language * University of Massachusetts Lowell, a research university * User-mode Linux, virtual machine software See also

* Unified Medical Language System (UMLS), a medical in ...
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 The Semantic Web (sometimes known as Web 3.0) is an extension of the World Wide Web The World Wide Web (WWW), commonly known as the Web, is an information system An information system (IS) is a formal, sociotechnical Sociotechnica ...

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 Visual Basic is a name for a family of programming languages from Microsoft. It may refer to: * Visual Basic (classic) The original Visual Basic (also referred to as Classic Visual Basic) is a third-generation programming language, third-gener ...
.


Within object-oriented analysis

In object-oriented analysis and in
UML UML may refer to: * Unified Modeling Language, a software modeling language * University of Massachusetts Lowell, a research university * User-mode Linux, virtual machine software See also

* Unified Medical Language System (UMLS), a medical in ...
, 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 method A method in object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "Object (computer science), objects", which can contain data and code: data in the form of Field (computer science), fi ...
s (or ''
virtual method In object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "Object (computer science), objects", which can contain data and code: data in the form of Field (computer science), fields (oft ...
s''). An abstract class may provide implementations of some methods, and may also specify virtual methods via
signatures 's signature is the most prominent on the United States Declaration of Independence and the Articles of Confederation. The name "John Hancock" or just "Hancock" has become a synonym for "signature" in the United States. A signature (; from la, ...
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 Java ( id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 147.7 million people, Java is the world's List of ...
, C# and
PHP PHP is a general-purpose scripting language A scripting language or script language is a programming language A programming language is a formal language comprising a Instruction set architecture, set of instructions that produce various k ...

PHP
, the keyword ''abstract'' is used. In
C++ C++ () is a general-purpose programming language In computer software, a general-purpose programming language is a programming language dedicated to a general-purpose, designed to be used for writing software in a wide variety of application ...

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 Interface or interfacing may refer to: Academic journals * Interface (journal), ''Interface'' (journal), by the Electrochemical Society * ''Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Lin ...
via a keyword in the language. In these languages,
multiple inheritance Multiple inheritance is a feature of some computer s in which an object or can features from more than one parent object or . It is distinct from single inheritance, where an object or class may only inherit from one particular object or class. ...

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 classIn object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "Object (computer science), objects", which can contain data and code: data in the form of Field (computer science), fields (often ...
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++ C++ () is a general-purpose programming language In computer software, a general-purpose programming language is a programming language dedicated to a general-purpose, designed to be used for writing software in a wide variety of application ...

C++
is an example of a language that supports both inner classes and inner types (via ''
typedef typedef is a reserved keyword in the programming language A programming language is a formal language In logic, mathematics, computer science, and linguistics, a formal language consists of string (computer science), words whose symbol (fo ...
'' 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 variable In computer programming Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a specific task. Programming involves tasks such as: analysis, generat ...
s declared within its enclosing function, but may not access the function's
automatic variable __NOTOC__ In computer programming Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a specific task. Programming involves tasks such as: analysis ...
s.


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 A design pattern is the re-usable form of a solution to a design problem. The idea was introduced by the architect Christopher Alexander Christopher Wolfgang Alexander (born 4 October 1936 in Vienna, Austria) is a widely influential British-Am ...
or describe particular kinds of classes. Metaclasses are often used to describe
framework Framework may refer to: Computing * Ajax framework * Application framework, used to implement the structure of an application for an operating system * Architecture framework * Content management framework, reusable components of a content manag ...
s. In some languages, such as
Python PYTHON was a Cold War contingency plan of the Government of the United Kingdom, British Government for the continuity of government in the event of Nuclear warfare, nuclear war. Background Following the report of the Strath Committee in 1955, the ...
,
Ruby A ruby is a pink-ish red to blood-red colored gemstone A gemstone (also called a fine gem, jewel, precious stone, or semi-precious stone) is a piece of mineral In geology and mineralogy, a mineral or mineral species is, broadly spea ...
or
Smalltalk Smalltalk is an object-oriented programming, object-oriented, dynamically typed reflection (computer science), reflective programming language. Smalltalk was created as the language underpinning the "new world" of computing exemplified by "human ...

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 The Common Lisp Object System (CLOS) is the facility for object-oriented programming Object-oriented programming (OOP) is a programming paradigm Programming paradigms are a way to classify programming languages based on their features. ...
(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 in C# or as in Java or PHP. For example, Java's 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 In computing, executable code, an executable file, or an executable program, sometimes simply referred to as an executable or binary, causes a computer "to perform indicated tasks according to encoded instruction (computer science), instructi ...
cannot be changed by customers. Developers can often change some classes, but typically cannot change standard or built-in ones. In
Ruby A ruby is a pink-ish red to blood-red colored gemstone A gemstone (also called a fine gem, jewel, precious stone, or semi-precious stone) is a piece of mineral In geology and mineralogy, a mineral or mineral species is, broadly spea ...
, all classes are open. In
Python PYTHON was a Cold War contingency plan of the Government of the United Kingdom, British Government for the continuity of government in the event of Nuclear warfare, nuclear war. Background Following the report of the Strath Committee in 1955, the ...
, classes can be created at runtime, and all can be modified afterwards. 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
mixin In object-oriented programming languages, a mixin (or mix-in) is a class that contains methods for use by other classes without having to be the parent class of those other classes. How those other classes gain access to the mixin's methods depen ...
s, 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 might provide a method called when included in classes and 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 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 generator In computing, code generation is the process by which a compiler's code generator converts some intermediate representation of source code into a form (e.g., machine code) that can be readily executed by a machine. Sophisticated compilers typicall ...
s, 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 Editing is the process of selecting and preparing written Writing is a medium of human communication Communication (from Latin ''communicare'', meaning "to share") is the act of developing Semantics, meaning among Subject (philosoph ...
. * Enables
separation of concerns In computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of compu ...
, in a way similar to
aspect-oriented programming In computing Computing is any goal-oriented activity requiring, benefiting from, or creating computing machinery. It includes the study and experimentation of algorithmic processes and development of both computer hardware , hardware and sof ...
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 Smalltalk is an object-oriented programming, object-oriented, dynamically typed reflection (computer science), reflective programming language. Smalltalk was created as the language underpinning the "new world" of computing exemplified by "human ...

Smalltalk
under the name of ''Class Extensions'' for considerable time. With the arrival of the .NET framework 2,
Microsoft Microsoft Corporation is an American multinational corporation, multinational technology company, technology corporation which produces Software, computer software, consumer electronics, personal computers, and related services. Its best-know ...

Microsoft
introduced partial classes, supported in both C# 2.0 and Visual Basic 2005.
WinRT Windows Runtime (WinRT) is a platform-agnostic component and application architecture first introduced in Windows 8 and Windows Server 2012 in 2012. It is implemented in C++ and officially supports development in C++ (via C++/WinRT, C++/CX or WRL) ...
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 Objective-C is a general-purpose, object-oriented Object-oriented programming (OOP) is a programming paradigm Program, programme, programmer, or programming may refer to: Business and management * Program management, the process of m ...
, 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 @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 #import "NSData+base64.h" int main(int argc, char *argv[]) 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 A prototype is an early sample, model, or release of a product built to test a concept or process. It is a term used in a variety of contexts, including semantics Semantics (from grc, σημαντικός ''sēmantikós'', "significant") ...
or
factory A factory, manufacturing plant or a production plant is an Industry (manufacturing), industrial site, often a complex consisting of several buildings filled with Outline of industrial machinery, machinery, where workers manufacturing, manufactu ...
metaobjectIn computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of Algorith ...
s that represent run-time information about classes, or even represent metadata that provides access to
reflectionReflection or reflexion may refer to: Philosophy * Self-reflection Science * Reflection (physics), a common wave phenomenon ** Specular reflection, reflection from a smooth surface *** Mirror image, a reflection in a mirror or in water ** Signal r ...
facilities and ability to manipulate data structure formats at run-time. Many languages distinguish this kind of
run-time type information In computer programming, run-time type information or run-time type identification (RTTI) is a feature of the C++ programming language that exposes information about an object's data type at Run time (program lifecycle phase), runtime. Run-time typ ...
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
metaobjectIn computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of Algorith ...
representing the class Person, then instances of class Person can be created by using the facilities of the Human
metaobjectIn computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of Algorith ...
.


See also

*
Class-based programming Class-based programming, or more commonly class-orientation, is a style of object-oriented programming Object-oriented programming (OOP) is a programming paradigm Programming paradigms are a way to classify programming languages based ...
*
Class diagram In software engineering Software engineering is the systematic application of engineering Engineering is the use of scientific principles to design and build machines, structures, and other items, including bridges, tunnels, roads, vehic ...

Class diagram
(UML) *
List of object-oriented programming languages This is a list of notable programming languages A programming language is a formal language In mathematics Mathematics (from Ancient Greek, Greek: ) includes the study of such topics as quantity (number theory), mathematical structure ...
*
Mixin In object-oriented programming languages, a mixin (or mix-in) is a class that contains methods for use by other classes without having to be the parent class of those other classes. How those other classes gain access to the mixin's methods depen ...
*
Object-oriented programming Object-oriented programming (OOP) is a programming paradigm Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. Some paradigms are concerned mai ...
*
Prototype-based programming Prototype-based programming is a style of object-oriented programming Object-oriented programming (OOP) is a programming paradigm Programming paradigms are a way to classify programming languages based on their features. Languages can ...
*
Trait (computer programming) In computer programming Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a specific task. Programming involves tasks such as: analysis, generat ...


Notes


References

* * *


Further reading


Abadi; Cardelli: A Theory of Objects

ISO/IEC 14882:2003 Programming Language C++, International standard


by Brian Foote * Meyer, B.: "Object-oriented software construction", 2nd edition, Prentice Hall, 1997, * Rumbaugh et al.: "Object-oriented modeling and design", Prentice Hall, 1991, {{DEFAULTSORT:Class (Computer Programming) Programming constructs Programming language topics