Class (computer programming): Difference between revisions

Content deleted Content added
mNo edit summary
 
Line 1:
{{Short description|Specification of an object}}
In [[object-oriented programming]], a '''class''' consists of [[Information hiding|encapsulated]] [[instance variable]]s and [[subprogram]]s, the methods mentioned below. A Class describes the rules by which [[Object (object-oriented programming)|objects]] behave; these objects are referred to as "[[instance]]s" of that class. A class specifies the structure of data which each instance contains as well as the [[Method (computer science)|methods]] ([[Function (computer science)|functions]]) which manipulate the data of the object; such methods are sometimes described as "[[behavior]]". A class is the most specific [[datatype|type]] of an object in relation to a specific [[layer]]. As a datatype, a class is a compile-time construct. A language may also support [[prototype]] or [[factory]] objects that represent run-time information about classes, but these should not be confused with classes, as these often do not include all information about classes due to concerns with space consumption.
 
In [[object-oriented programming]], a '''class''' defines the shared aspects of [[Object (computer science)|objects]] created from the class. The capabilities of a class differ between [[programming language]]s, but generally the shared aspects consist of state ([[Variable (computer science)|variables]]) and behavior ([[Method (computer programming)|methods]]) that are each either associated with a particular object or with all objects of that class.{{sfn|Gamma|Helm|Johnson|Vlissides|1995|p=14}}{{sfn|Bruce|2002|loc=2.1 Objects, classes, and object types, {{Google books|9NGWq3K1RwUC|Objects, classes, and object types|page=18|plainurl=yes}}}}
Classes are sometimes described as "[[blueprint]]s"; instances of a class will have certain aspects in common. One might describe a "class of [[animal]]s" ([[dog]]s), or a "class of [[object|tangible objects]]" ([[computer]]s). One of the benefits of programming with classes is that all instances of a particular class will follow the defined behaviour of said class. For example: if [[human]]s are a class, then each person is an instance of an object of the human class. Each person is generally alike; but varies in such properties as "height" and "weight". The class would list such instance variables; and also define, via methods, the [[action (philosophy)|action]]s which humans can perform: "run", "jump", "sleep", "throw object", etc.
 
Object state can differ between each instance of the class whereas the class state is shared by all of them. The object methods include access to the object state (via an implicit or explicit parameter that references the object) whereas class methods do not.
== Interface to a class ==
 
If the language supports [[Inheritance (object-oriented programming)|inheritance]], a class can be defined based on another class with all of its state and behavior plus additional state and behavior that further specializes the class. The specialized class is a ''sub-class'', and the class it is based on is its ''superclass''.
A class implements (or realizes) one or more [[interface (computer science)|interface]]s. Each interface specifies [[operation]] signatures of some of the [[method]]s of the class. The methods of a class can either be used via one of its interfaces or directly. An interface of a class describes the possible behaviours of objects of the class from user's point of view. Multiple classes can implement the same interface. Partial implementations of interfaces are not allowed, that is, every operation has to have an implementation. However usually not every combination of parameter values need to be supported.
 
In purely object-oriented programming languages, such as [[Java (programming language) | Java]] and [[C Sharp (programming language)|C#]], all classes might be part of an inheritance tree such that the root class is <code>Object</code>, meaning all objects instances are of <code>Object</code> or implicitly extend <code>Object</code>.
Each interface of the class is associated with a type of [[object reference]]s referring to the interface, through which methods of objects can be invoked. Each reference points to a single instance of the class.
Each reference has a [[lifetime]], which specifies how long the reference can be used, usually bound to the time when some specific operations are invoked via the interface. It is assumed that there is a mechanism for accessing the object with a valid object reference. However, the object reference does not necessarily point to any single ___location, since the same object can be located at different times in different places.
 
==Attributes==
The [[object-oriented programming]] methodology is designed in such way that the operations of any interface of a class are usually chosen to be independent of each other. This means that 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 rely that the operations of an interface are available for use whenever the client holds a valid reference to the object. This will also result in a [[client-server]] (or layered) design where servers do not depend in any
way of the clients.
 
===Object lifecycle===
The methods that are not in any of the interfaces of a class are private to the class, and not intended to be depended on by other classes.
 
As an [[Instance (computer science)|instance]] of a class, an object is constructed from a class via ''instantiation''. Memory is allocated and initialized for the object state and a [[Reference (computer science)|reference]] to the object is provided to consuming code. The object is usable until it is destroyed {{endash}} its state memory is de-allocated.
The "set of all interfaces of a class" is sometimes called the interface of the class.
 
Most languages allow for custom logic at lifecycle events via a [[Constructor (object-oriented programming)|constructor]] and a [[Destructor (computer programming)|destructor]].
The internal data structures defined as part of a class are not considered to be part of its interface. Rather, public ''accessor'' methods can be used to inspect or alter object data. The various [[object-oriented]] programming languages enforce this to various degrees. For example, [[Java programming language|Java]] does not allow the programmer to access the private data of a class at all, whereas in languages like [[Objective-C]] or [[Perl]] the programmer can do what they want. In [[C_plus_plus|C++]], private methods are visible but not accessible in the interface; however they are commonly made invisible by explicitly declaring fully abstract classes that represent the interfaces of the class.
 
===Type===
== Structure of a class ==
 
An object expresses [[data type]] as an interface {{endash}} the type of each member variable and the signature of each [[member function]] (method). A class defines an implementation of an interface, and instantiating the class results in an object that exposes the implementation via the interface.{{sfn|Gamma|Helm|Johnson|Vlissides|1995|p=17}} In the terms of type theory, a class is an implementation{{mdashb}}a ''concrete'' [[data structure]] and collection of subroutines{{mdashb}}while a type is an [[Protocol (object-oriented programming)|interface]]. Different (concrete) classes can produce objects of the same (abstract) type (depending on type system). For example, the type (interface) {{Mono|Stack}} might be implemented by {{Mono|SmallStack}} that is fast for small stacks but scales poorly and {{Mono|ScalableStack}} that scales well but has high overhead for small stacks.
[[Image:oop-uml-class-example.png|frame|right|UML notation for classes]]
 
=== <span class="anchor" id="PROPERTY"></span>Structure ===
A class contains a description of data ("[[state (object-oriented programming)|state]]") stored in the objects of the class. The state of an object is stored in some resource, such as memory or a file. The storage is assumed to be located in a specific ___location, such that it is possible to access the object via [[reference (computer science)|reference]]s to the [[identity (object-oriented programming)|identity]] of the objects. However, the actual storage ___location associated with an object may change with time. In such situations, the identity of the object does not change. The state is encapsulated and every access to the state occurs via methods of the class.
[[File:oop-uml-class-example.svg|frame|right|[[Unified Modeling Language|UML]] notation for classes]]
 
A class contains [[Data (computing)|data]] [[Field (computer science)|field]] descriptions (or ''[[property (programming)|properties]]'', ''[[field (computer science)|fields]]'', ''data [[member variable|members]]'', or ''[[attribute (computing)|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 (programming language)|Python]] use associative key-value containers.<ref name="pythondata model">{{cite web|url=https://docs.python.org/reference/datamodel.html|title=3. Data model|work=The Python Language Reference|publisher=Python Software Foundation|access-date=2012-04-26}}</ref>
A class implements its interfaces by specifying methods that describe what operations can be performed on the data stored in the objects of the class. Each method specifies only tasks that are related to the stored data. Multi-methods can be used when a single task requires access to many objects' data.
 
ASome classprogramming alsolanguages describessuch aas setEiffel support specification of [[invariant (computer science)|invariant]]s that are preserved by every method in the class. An invariant is a constraint on the state of an object that should be satisfied by every object of the class. The main purpose of the invariants is to establish what objects belong to the class. An |invariant is what distinguishes [[datatype]]s and classes from each other, that is, a class does not allow use of all possible values for the state of the object, only those that are well-defined by the semantics of the intended use of the datatype. The set of supported methods often implicitly establishes an invariant. Some programming languages support specification of invariants as part of the definition of the class, and enforce them viathrough the type system. [[Encapsulation (object-oriented programming)|Encapsulation]] of state is necessary for being able to enforce the invariants of the class.
 
=== Behavior ===
An implementation of a class specifies [[constructor]] and [[destructor]] functions that allow creation and destruction of objects of the class. A constructor that takes arguments can be used to create an object from [[data]]. A destructor that returns a value can be used to obtain a [[representation]] of an object of a class. The main purpose of a constructor is to establish the invariant of the class, failing if the invariant isn't valid. The main purpose of a destructor is to destroy the identity of the object, invalidating any references in the process. Constructors and destructors are also sometimes used to reserve and release resources associated with the object.
{{Main|Method (computer programming)}}
<!-- This section used to contain info on Java interfaces. If you wish to view it (to, say, move to another page), the last revision before the removal of this info is http://en.wikipedia.org/w/index.php?title=Class_(computer_science)&oldid=165562113 -->
 
The behavior of a class or its instances is defined using [[Method (computer programming)|methods]]. Methods are [[subroutine]]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.{{sfn|Booch|1994|p=86-88}}<!-- (Note: Some languages allow direct access to instance variables ([[C++]])). --> 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.<ref>{{cite web|url=http://www.cplusplus.com/doc/tutorial/classes/|title=Classes (I)|work=C++ Language Tutorial|publisher=cplusplus.com|access-date=2012-04-29}}</ref><ref>{{cite web|url=http://www.cplusplus.com/doc/tutorial/classes2/|title=Classes (II)|work=C++ Language Tutorial|publisher=cplusplus.com|access-date=2012-04-29}}</ref>
A class can also implement a set of auxiliary [[function (programming)|functions]], sometimes called class functions or static methods. Static methods are often used to find, create or destroy objects of the class. Constructors and destructors are sometimes specified as static methods. Often, mechanisms for sending an object to another ___location or changing the class of an object are specified as static methods.
 
=== Class interface ===
==Subclasses and superclasses==
{{main|Interface (object-oriented programming)}}
{{Further|Interface (computing)}}
 
Every class ''implements'' (or ''realizes'') an interface by providing [[#Structure|structure]] and behavior. Structure consists of data and state, and behavior consists of code that specifies how methods are implemented.{{sfn|Booch|1994|p=105}} 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_and_Concrete|abstract class]] can define an interface without providing an implementation.
Classes are often related in some way. The most popular of these relations is [[inheritance (object-oriented programming)|inheritance]], which involves '''subclasses''' and '''superclasses''', also known respectively as '''child classes''' (or '''derived classes''') and '''parent classes''' (or '''base classes'''). If [car] was a class, then [Jaguar] and [Porsche] might be two sub-classes. If [Button] is a subclass of [Control], then all buttons are controls. Subclasses usually consists of several kinds of modifications to the base class: addition of new instance variables, addition of new methods and [[overriding]] of existing methods to support the new instance variables.
 
Languages that support class inheritance also allow classes to inherit interfaces from the classes that they are derived from.
Conceptually, a superclass should be considered as a common part of its subclasses. This factoring of commonality is one mechanism for providing [[reuse]]. Thus, extending a superclass by modifying the existing class is also likely to narrow its applicability in various situations. In [[Object-oriented design]], careful balance between applicability and functionality of superclasses should be considered. Subclassing is different from [[subtyping]] in that subtyping deals with common behaviour whereas subclassing is concerned with common structure.
 
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".
Some [[programming language|programming languages]] (for example [[C Plus Plus|C++]]) allow [[multiple inheritance]] -- they allow a child class to have more than one parent class. This technique has been criticized by some for its unnecessary complexity and being difficult to implement efficiently, though some projects have certainly benefited from its use. [[Java programming language|Java]], for example has no multiple inheritance, its designers feeling that this would be more trouble than it was worth.
 
In languages that support [[#Information hiding and encapsulation|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 [[Mutator method|getter and setter methods]]); any private members or internal data structures are not intended to be depended on by external<!--client--> code and thus are not part of the interface.
Sub- and superclasses are considered to exist within a [[hierarchy (object-oriented programming)|hierarchy]] defined by the inheritance relationship. If multiple inheritance is allowed, this hierarchy is a [[directed acyclic graph]] (or DAG for short), otherwise it is a [[tree (graph theory)|tree]]. The hierarchy has classes as nodes and inheritance relationships as links. The levels of this hierarchy are called [[layer]]s or [[level of abstraction|levels of abstraction]]. Classes in the same level are more likely to be [[association (object-oriented_programming)|associated]] than classes in different levels.
 
Object-oriented programming methodology<!--is designed in such a way--> 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<!--holds a valid reference--> has access to the object.<ref>{{Cite book|title=New Perspectives on Computer Concepts 2016, Comprehensive |publisher= Cengage Learning |last=Parsons |first= June Jamrich|isbn=9781305271616|___location=Boston, MA|oclc=917155105|date=2015-06-22}}</ref>
There are two slightly different points of view as to whether subclasses of the same class are required to be disjoint. Sometimes, subclasses of a particular class are considered to be completely disjoint. That is, every instance of a class has exactly one ''most-derived class'', which is a subclass of every class that the instance has. This view does not allow dynamic change of object's class, as objects are assumed to be created with a fixed most-derived class. The basis for not allowing changes to object's class is that the class is a compile-time type, which does not usually change at runtime, and polymorphism is utilised for any dynamic change to the object's behaviour, so this ability is not necessary. And design that does not need to perform changes to object's type will be more robust and easy-to-use from the point of view of the users of the class.
 
; Class interface example
From another point of view, subclasses are not required to be disjoint. Then there is no concept of a most-derived class, and all types in the inheritance hierarchy that are types of the instance are considered to be equally types of the instance. This view is based on a dynamic classification of objects, such that an object may change its class at runtime. Then object's class is considered to be its ''current'' structure, but changes to it are allowed. The basis for allowing object's class to change is performance. It's more efficient to allow changes to object's type, since references to the existing instances do not need to be replaced with references to new instances when the class of the object changes. However, this ability is not readily available in all programming languages.
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 color, which together comprise its structure. A class represents the full description of a television, including its attributes (structure) and buttons (interface).
==Reasons for implementing classes==
 
Getting the total number of televisions manufactured could be a ''static method'' of the television class. This method is associated with the class, yet is outside the ___domain of each instance of the class. A static method that finds a particular instance out of the set of all television objects is another example.
Classes, when used properly, can accelerate development by reducing redundant code entry, testing and bug fixing. If a class has been thoroughly tested and is known to be a solid work, it stands to reason that implementing that class or extending it will reduce if not eliminate the possibility of bugs propagating into the code. In the case of extension new code is being added so it also requires the same level of testing before it can be considered solid.
 
=== Member accessibility ===
Another reason for using classes is to simplify the relationships of interrelated data. Rather than writing code to repeatedly draw a GUI window on the terminal screen, it is simpler to represent the window as an object and tell it to draw itself as necessary. With classes, GUI items that are similar to windows (such as dialog boxes) can simply inherit most of their functionality and data structures from the window class. The programmer then need only add code to the dialog class that is unique to its operation. Indeed, GUIs are a very common and useful application of classes, and GUI programming is generally much easier with a good class framework.
{{redirect|Private member|other uses|Private members club|and|Private member's bill}}
{{Further|Information hiding}}
 
The following is a common set of [[access specifiers]]:<ref name="JavaAccessControl">{{cite web| url=http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html|title=Controlling Access to Members of a Class|work=The Java Tutorials|publisher=Oracle|access-date=2012-04-19}}</ref>
==Categories of Classes==
 
* ''Private'' (or ''class-private'') restricts access to the class itself. Only methods that are part of the same class can access private members.
An '''abstract class''', or ''abstract base class'' (ABC), is one that is designed ''only'' as a [[class (object-oriented programming)|parent class]] and from which [[class (object-oriented programming)|child classes]] may be derived, and which is not itself suitable for [[instance|instantiation]]. Abstract classes are often used to represent [[abstract]] concepts or entities. The incomplete features of the abstract class are then shared by a group of sibling sub-classes which add different variations of the missing pieces. In C++, an abstract class is
* ''Protected'' (or ''class-protected'') allows the class itself and all its subclasses to access the member.
defined as a class having at least one virtual function without an implementation.
* ''Public'' means that any code can access the member by its name.
 
Although many object-oriented languages support the above access specifiers,<!-- {{Citation needed|reason=This is fairly obvious, but it needs to be cited--could even use a few links even to articles within Wikipedia.|date=April 2012}} --> their semantics may differ.
Abstract classes are superclasses which contain [[abstract method]]s and are defined such that subclasses are to extend them by implementing the [[method (computer science)|method]]s. The [[behavior]]s defined by such a class are ''"generic"'' and much of the class will be [[definition|undefined]] and unimplemented. Before a class derived from an abstract class can be instantiated, it must implement particular methods for all the abstract methods of its parent classes.
 
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 method]]s can be used to inspect or alter such private data.
In [[computing]], when specifying an '''abstract class''', the programmer is referring to a [[Class (computer science)|class]] which has elements that are meant to be implemented by inheritance. The [[Abstraction (computer science)|abstraction]] of the class [[Method (computer science)|methods]] to be implemented by the sub-classes is meant to simplify [[software development]].
 
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 runtime (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 the client code will be prevented by the type checker.<ref>{{cite web|url=https://www.securecoding.cert.org/confluence/display/cplusplus/OOP08-CPP.+Do+not+return+references+to+private+data|title=OOP08-CPP. Do not return references to private data|work=CERT C++ Secure Coding Standard|publisher=Carnegie Mellon University|date=2010-05-10|access-date=2012-05-07|archive-url=https://web.archive.org/web/20151003162754/https://www.securecoding.cert.org/confluence/display/cplusplus/OOP08-CPP.+Do+not+return+references+to+private+data|archive-date=2015-10-03|url-status=dead}}</ref>
A '''concrete class''', however, is a [[Class (computer science)|class]] for which entities (instances) may be created. This contrasts with abstract classes which can not be [[instance|instantiated]] because it defeats its purpose of being an 'abstract'.
 
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 [[Runtime (program lifecycle phase)|runtime]]. For example, the [[Java (programming language)|Java]] language does not allow client code that accesses the private data of a class to compile.<ref>
==Object-based programming==
{{cite web|url=http://introcs.cs.princeton.edu/java/11cheatsheet/errors.pdf |archive-url=https://web.archive.org/web/20111018094803/http://introcs.cs.princeton.edu/java/11cheatsheet/errors.pdf |archive-date=2011-10-18 |url-status=live|title=2.2 Identifiers|work=Compile and Runtime Errors in Java|first=Mordechai|last=Ben-Ari|date=2007-01-24|access-date=2012-05-07}}</ref><!-- whereas in languages like [[Objective-C]] or [[Perl]] client code is not restricted.--> 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.<ref name="cppinterface">{{cite web|url=http://www.drdobbs.com/cpp/184410630|title=C++ Interfaces|last=Wild|first=Fred|work=Dr. Dobb's|publisher=UBM Techweb|access-date=2012-05-02}}</ref>
Some languages have objects, but no classes; in such "[[object-based programming|object-based languages]]", objects are not restricted to class structure.
Object-based languages with this property do not provide the structural benefits of statically type checked interfaces for objects.
 
Some languages feature other accessibility schemes:
==C++==
* ''Instance vs. class accessibility'': [[Ruby (programming language)|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.<ref>{{cite web |url=https://docs.ruby-lang.org/en/master/syntax/modules_and_classes_rdoc.html#label-Visibility |title=modules_and_classes: Visibility}}</ref>
In [[C Plus Plus|C++]], an abstract class is a class having at least one pure virtual function.
* ''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.<ref>{{cite web|url=http://www.cplusplus.com/doc/tutorial/inheritance/|title=Friendship and inheritance|work=C++ Language Tutorial|publisher=cplusplus.com|access-date=2012-04-26}}</ref>
They can not be instantiated and will generate an error if an attempt is made. They are meant to function as stubs, allowing the programmer to identify what modules of functions (behaviour or methods) are needed without having to actually implement them. This is in line with [[OOP]]'s philosophy of allowing the programmer to concentrate on how an object should behave without going into the actual detail.
* ''Path-based'': Java supports restricting access to a member within a [[Java syntax#Access modifiers|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 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.<ref name=JavaAccessControl/>
 
====Inheritance====
Most [[Object-oriented programming language|object oriented programming languages]] allow the [[programmer]] to specify which classes are considered abstract and will not allow these to be instantiated (in [[Java programming language|Java]], for example, the keyword ''abstract'' is used). This also
enables the programmer to focus on planning and design. The actual
implementation of course is to be done in the derived classes.
 
See, for example, [[class{{Main|Inheritance (object-oriented programming)]]|Superclass for(computer ascience)|Subclass unified(computer discussion.science)}}
 
Conceptually, a superclass is a [[superset]] of its subclasses. For example, {{Mono|GraphicObject}} could be a superclass of {{Mono|Rectangle}} and {{Mono|Ellipse}}, while {{Mono|Square}} would be a subclass of {{Mono|Rectangle}}. These are all [[Subset|subset relations]] in set theory as well, i.e., all squares are rectangles but not all rectangles are squares.
== Metaclasses ==
 
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 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 an engine or body as a subclass of a car.
Metaclasses are classes whose instances are classes. A metaclass describes a common structure of a collection of classes. A metaclass can implement a [[design pattern (computer science)|design pattern]] or describe a shorthand for particular kinds of classes. Metaclasses are often used to describe [[framework]]s.
 
In [[object-oriented modeling]] these kinds of relations are typically modeled as object properties. In this example, the {{Mono|Car}} class would have a property called {{Mono|parts}}. {{Mono|parts}} would be typed to hold a collection of objects, such as instances of {{Mono|Body}}, {{Mono|Engine}}, {{Mono|Tires}}, etc.
== Examples ==
Object modeling languages such as [[Unified Modeling Language|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 besides the basic data definitions for the objects, such as error checking on [[Mutator method|get and set methods]].<ref>{{cite web|title=UML-to-Java transformation in IBM Rational Software Architect editions and related software|url=http://www.ibm.com/developerworks/rational/library/08/1202_berfeld/|publisher=[[IBM]]|date=2 December 2008|first=Marya|last=Berfeld|access-date=20 December 2013}}</ref>
=== Examples in C++ ===
==== Example 1 ====
 
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 did not 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.<ref>{{cite book|last=Jacobsen|first=Ivar|title=Object Oriented Software Engineering|year=1992|publisher=Addison-Wesley ACM Press|isbn=0-201-54435-0|pages=[https://archive.org/details/objectorientedso00jaco/page/43 43–69]|author2=Magnus Christerson|author3=Patrik Jonsson|author4=Gunnar Overgaard|url=https://archive.org/details/objectorientedso00jaco/page/43}}</ref>
class example {
// this is a class
};
 
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.
This example shows how to define a [[C Plus Plus|C++]] class. It has no data, and performs no functions; it only contains the comment, "this is a class".
 
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|Web Ontology Language (OWL)]] are designed to support it.
==== Example 2 ====
 
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 protocol]]s. 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 rationale 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.<ref>{{cite web|url=http://www.w3.org/2001/sw/BestPractices/SE/ODSD/|title=A Semantic Web Primer for Object-Oriented Software Developers|last1=Knublauch|first1=Holger|last2=Oberle|first2=Daniel|last3=Tetlow|first3=Phil|last4=Wallace|first4=Evan|publisher=[[W3C]]|date=2006-03-09|access-date=2008-07-30}}</ref>
class Abstract
{
public:
virtual void MyVirtualMethod() = 0;
};
 
Although many class-based languages support inheritance, inheritance is not an intrinsic aspect of classes. An [[object-based language]] (i.e. [[Classic Visual Basic]]) supports classes yet does not support inheritance.<!-- do not provide the structural benefits of statically type-checked interfaces for objects. This is because, in object-based languages, it is possible to use and extend data structures and attach methods to them at runtime. This precludes the compiler or interpreter from being able to check the type information specified in the source code as the type is built dynamically and not defined statically. Most of these languages allow for ''instance behavior'' and complex ''operational polymorphism'' (see [[dynamic dispatch]] and [[Polymorphism (computer science)|polymorphism]])
class Concrete : public Abstract
{
public:
void MyVirtualMethod()
{
//do something
}
};
 
== Inter-class relationships ==
An object of class Abstract can not be created because the function MyVirtualMethod has not been defined (the =0 is C++ syntax for a pure virtual function, a function that must be part of any derived concrete class but is not defined in the abstract base class. The Concrete class is a concrete class because its functions (in this case, only one function) have been declared and implemented.
 
A programming language may support various class relationship features.
==== Example 3 ====
 
=== Compositional ===
#include <string>
using std::string;
class InetMessage
{
string m_subject, m_to, m_from;
public:
InetMessage (const string& subject,
const string& to,
const string& from);
string subject () const;
string to () const;
string from () const;
};
</pre>
 
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.{{sfn|Booch|1994|p=180}} 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 [[Object lifetime|lifetime]]. If the components are contained by reference, they may not have a similar lifetime.{{sfn|Booch|1994|p=128-129}} For example, in Objective-C 2.0:
=== Examples in Java ===
==== Example 1 ====
 
<syntaxhighlight lang="objc">
public class Example1
@interface Car : NSObject
{
// This is a Java class, it automatically extends the class Object
}
 
@property NSString *name;
This example shows the simplest [[Java programming language|Java]] class possible.
@property Engine *engine
@property NSArray *tires;
 
@end
==== Example 2 ====
</syntaxhighlight>
 
This {{Mono|Car}} class ''has'' an instance of {{Mono|NSString}} (a [[string (computer science)|string]] object), {{Mono|Engine}}, and {{Mono|NSArray}} (an array object).
public class Example2 extends Example1
{
// This is a class that extends the class created in Example 1.
protected int data;
public Example2()
{
// This is a constructor for the class. It does not have a return type.
data = 1;
}
public int getData()
{
return data;
}
public void setData(int d)
{
data = d;
}
}
 
=== Hierarchical ===
This example shows a class that has a defined constructor, one member data, and two accessor methods for that member data. It extends the previous example's class. Note that in Java all classes automatically extend the class Object. This allows you to write generic code to deal with objects of any type.
 
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 ''{{vanchor|superclasses|SUPERCLASS}}'') 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.{{sfn|Booch|1994|p=112}} 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 [[method overriding|override]] inherited methods if the language allows.
==See also==
* [[Instance|Instantiation]]
* [[Hierarchy (object-oriented programming)|Hierarchy]]
* [[Unified Modeling Language]] (UML)
 
Not all languages support multiple inheritance. For example, Java allows a class to implement multiple interfaces, but only inherit from one class.<ref name="javainterface">{{cite web| url=http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html|title=Interfaces|work=The Java Tutorials|publisher=Oracle|access-date=2012-05-01}}</ref> If multiple inheritance is allowed, the hierarchy is a [[directed acyclic graph]] (or DAG for short), otherwise it is a [[tree (graph theory)|tree]]. The hierarchy has classes as nodes and inheritance relationships as links. Classes in the same level are more likely to be [[association (object-oriented programming)|associated]] than classes in different levels. The levels of this hierarchy are called [[Layer (object-oriented design)|layers]] or levels of abstraction.
[[Category:Object-oriented programming]]
 
Example (Simplified Objective-C 2.0 code, from iPhone SDK):
[[de:Klasse (objektorientierte Programmierung)]]
<syntaxhighlight lang="objc">
[[ja:&#12463;&#12521;&#12473;]]
@interface UIResponder : NSObject //...
[[fi:Luokka]]
@interface UIView : UIResponder //...
[[lt:Klas&#279; (programavimas)]]
@interface UIScrollView : UIView //...
[[pl:Klasa abstrakcyjna]]
@interface UITableView : UIScrollView //...
[[sv:Klass (programmering)]]
</syntaxhighlight>
[[fr:Classe (informatique)]]
In this example, a UITableView ''is a'' UIScrollView ''is a'' UIView ''is a'' UIResponder ''is an'' NSObject.
[[zh:&#31867; (&#35745;&#31639;&#26426;&#31185;&#23398;)]]
 
===Modeling===
 
In [[object-oriented analysis and design|object-oriented analysis]] and in [[Unified Modelling Language]] (UML), an [[Association (object-oriented programming)|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.<ref name="ibmuml">{{cite web| url=http://www.ibm.com/developerworks/rational/library/content/RationalEdge/sep04/bell/|title=UML Basics: The class diagram|last=Bell|first=Donald|work=developer Works|publisher=IBM|access-date=2012-05-02}}</ref> Associations may be labeled according to their name or purpose.{{sfn|Booch|1994|p=179}}
 
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.<ref name=ibmuml/>
 
==Taxonomy==
 
There are many categories of classes, some of which overlap.
 
===Abstract and concrete===
<span class="anchor" id="Abstract_and_concrete_classes"></span><span class="anchor" id="Abstract_and_Concrete"></span>
{{see also|Abstract type}}
 
In a language that supports inheritance, an ''abstract class'', or ''abstract base class'' (''ABC''), is a class that cannot be directly instantiated. By contrast, a ''concrete class'' is a class that {{em|can}} be directly instantiated. Instantiation of an abstract class can occur only indirectly, via a concrete {{em|sub}}class.
 
An abstract class is either labeled as such explicitly or it may simply specify ''[[abstract method]]s'' (or ''[[virtual method]]s''). An abstract class may provide implementations of some methods, and may also specify virtual methods via [[Type signature|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.<ref name="cpppoly">{{cite web|url=http://www.cplusplus.com/doc/tutorial/polymorphism/
|title=Polymorphism|work=C++ Language Tutorial|publisher=cplusplus.com|access-date=2012-05-02}}</ref>
 
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 (programming language)|Java]], [[C Sharp (programming language)|C#]] and [[PHP]], the keyword ''abstract'' is used.<ref>{{cite web| url=http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html|title=Abstract Methods and Classes|work=The Java Tutorials|publisher=Oracle|access-date=2012-05-02}}</ref><ref>{{cite web|url=http://php.net/manual/en/language.oop5.abstract.php|title=Class Abstraction|work=PHP Manual|publisher=The PHP Group|access-date=2012-05-02}}</ref> 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).<ref name=cpppoly/>
 
A class consisting of only pure 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.<ref name=cppinterface/> Other languages, notably Java and C#, support a variant of abstract classes called an [[Interface (Java)|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.<ref name=javainterface/><ref>{{cite web |url=http://msdn.microsoft.com/en-us/library/ms173156.aspx |title=Interfaces (C# Programming Guide) |work=C# Programming Guide |publisher=Microsoft |access-date=2013-08-15}}</ref><ref>
{{cite web |url=http://msdn.microsoft.com/en-us/library/ms173149.aspx |title=Inheritance (C# Programming Guide) |work=C# Programming Guide |publisher=Microsoft |access-date=2012-05-02}}</ref>
<!--Abstract classes defined as interfaces are a much more specific use of the more general meaning of the term ''interface'', even as used in computer science, and the concept of interfaces has seen much use and popularity within the realm of languages that support object-orientation.-->
 
===Local and inner===
 
In some languages, classes can be declared in [[Scope (programming)|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 the 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).<ref>{{cite web |url=http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr061.htm |title=Nested classes (C++ only) |work=XL C/C++ V8.0 for AIX |publisher=IBM |access-date=2012-05-07}}</ref><ref>
{{cite web |url=http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr063.htm |title=Local type names (C++ only) |work=XL C/C++ V8.0 for AIX |publisher=IBM |access-date=2012-05-07}}</ref>
 
A ''local class'' is a class defined within a procedure or function. Such structure 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]]s declared within its enclosing function, but may not access the function's [[automatic variable]]s.<ref>{{cite web |url=http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr062.htm |title=Local classes (C++ only) |work=XL C/C++ V8.0 for AIX |publisher=IBM |access-date=2012-05-07}}</ref>
 
===Metaclass===
{{Main|Metaclass}}
 
A metaclass is a class where instances are classes.{{sfn|Booch|1994|p=133-134}} A metaclass describes a common structure of a collection of classes and can implement a [[design pattern (computer science)|design pattern]] or describe particular kinds of classes. Metaclasses are often used to describe [[software framework|framework]]s.<ref>{{Cite web|url=http://pharo.gforge.inria.fr/PBE1/PBE1ch14.html|title=13 Classes and metaclasses|website=pharo.gforge.inria.fr|access-date=2016-10-31|archive-date=2021-02-24|archive-url=https://web.archive.org/web/20210224193450/http://pharo.gforge.inria.fr/PBE1/PBE1ch14.html|url-status=dead}}</ref>
 
In some languages, such as [[Python (programming language)|Python]], [[Ruby (programming language)|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.<ref name="pythondata model"/><ref>{{cite web |url=https://docs.ruby-lang.org/en/master/Class.html |title=class Class}}</ref>
{{sfn|Booch|1994|p=134}}
The [[Common Lisp Object System]] (CLOS) provides [[Metaobject|metaobject protocols]] (MOPs) to implement those classes and metaclasses.<ref>{{cite web |url=http://www.alu.org/mop/concepts.html#introduction |title=MOP: Concepts |work=The Common Lisp Object System MetaObject Protocol |publisher=Association of Lisp Users |access-date=2012-05-08 |archive-url=https://web.archive.org/web/20101115095930/http://www.alu.org/mop/concepts.html#introduction |archive-date=2010-11-15 |url-status=dead}}</ref>
 
===Sealed===
<span class="anchor" id="Non-subclassable"></span><span class="anchor" id="Sealed"></span>
A sealed class cannot be subclassed. It is basically the opposite of an ''abstract'' class, which must be derived to be used. A sealed class is implicitly ''concrete''.
 
A class is declared as sealed via the keyword {{code|sealed|lang=csharp}} in C# or {{code|final|lang=java}} in Java or PHP. However, this concept should not be confused with classes in Java qualified with the keyword <code>sealed</code>, that only allow inheritance from selected subclasses.<ref>{{cite web |title=sealed (C# Reference) |url=http://msdn.microsoft.com/en-us/library/ms173149.aspx |access-date=2012-05-08 |work=C# Reference |publisher=Microsoft}}</ref><ref>
{{cite web |title=Writing Final Classes and Methods |url=http://docs.oracle.com/javase/tutorial/java/IandI/final.html |access-date=2012-05-08 |work=The Java Tutorials |publisher=Oracle}}</ref><ref>
{{cite web |title=PHP: Final Keyword |url=http://php.net/manual/en/language.oop5.final.php |access-date=2014-08-21 |work=PHP Manual |publisher=The PHP Group}}</ref><ref>{{Cite web |title=Sealed Classes |url=https://docs.oracle.com/en/java/javase/22/language/sealed-classes-and-interfaces.html |access-date=2025-07-07 |website=Oracle Help Center |language=en-US}}</ref>
 
For example, Java's {{Java|String}} class is marked as ''final''.<ref>{{cite web |url=http://docs.oracle.com/javase/7/docs/api/java/lang/String.html |title=String (Java Platform SE 7) |work=Java Platform, Standard Edition 7: API Specification |publisher=Oracle |access-date=2012-05-08}}</ref>
 
Sealed classes may allow a compiler to perform optimizations that are not available for classes that can be subclassed.<ref>{{cite web |last1=Brand |first1=Sy |title=The Performance Benefits of Final Classes |url=https://devblogs.microsoft.com/cppblog/the-performance-benefits-of-final-classes/ |website=Microsoft C++ team blog |date=2 March 2020 |publisher=Microsoft |access-date=4 April 2020}}</ref>
<!-- The following goes without saying, i.e., it says nothing but to hint that "abstract" and "concrete" are an "either but not both" concept. 'abstract' and 'concrete' are defined already above.-->
<!-- While it is impossible in any object-oriented language to have a class that is both abstract and concrete, it may be possible to have an abstract partial class -->
<!-- The following seemingly belongs in the 'method' article -->
<!-- It is also possible not to declare the whole class as such, but only the [[Override (object-oriented programming)|override]] as sealed. This classes are used because of efficiency concerns (can be called like static classes) and security (avoids inadvertent modification of the class semantics).<ref>{{cite web |access-date=2011-08-03 |date=2002-03-25 |first=Hanspeter |last=Mössenböck |page=17 |publisher=Institut für Systemsoftware, Johannes Kepler Universität Linz, Fachbereich Informatik |title=Advanced C#: Overriding of Methods |url=http://ssw.jku.at/Teaching/Lectures/CSharp/Tutorial/Part2.pdf}}
</ref> -->
 
===Open<span class="anchor" id="Open class"></span>===
 
An open class 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 (programming language)#Open classes|Ruby]], all classes are open. In [[Python (programming language)|Python]], classes can be created at runtime, and all can be modified afterward.<ref>{{cite web|title=9. Classes|url=https://docs.python.org/3.3/tutorial/classes.html|website=The Python Tutorial|publisher=Python.org|access-date=3 March 2018|quote=As is true for modules, classes partake of the dynamic nature of Python: they are created at runtime, and can be modified further after creation.}}</ref> [[Objective-C#Categories|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.
 
===Mixin===
 
Some languages have special support for [[mixin]]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 {{Mono|UnicodeConversionMixin}} might provide a method called {{Mono|unicode_to_ascii}} when included in classes {{Mono|FileReader}} and {{Mono|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|source-code]] file or across multiple files.<ref name="mspartial">{{Citation|url=https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/partial-classes-and-methods|title=Partial Classes and Methods|work=C# Programming Guide|date=2015-09-19|author1=mairaw|author2=BillWagner|author3=tompratt-AQ|publisher=Microsoft|access-date=2018-08-08}}</ref> The pieces are merged at compile time, making compiler output the same as for a non-partial class.
 
The primary motivation for the introduction of partial classes is to facilitate the implementation of [[Automatic programming|code generators]], such as [[visual designer]]s.<ref name="mspartial"/> 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. <ref>{{cite web | url=https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/partial-classes-and-methods | title=Partial Classes and Members - C# }}</ref>
 
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 [[source code editor|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.<!-- (This enabling may be considered by some or most to be a detriment rather than a benefit for SoC can apply to programmers also).-->
 
Partial classes have existed in [[Smalltalk]] under the name of ''Class Extensions'' for considerable time. With the arrival of the [[.NET Framework|.NET framework 2]], [[Microsoft]] introduced partial classes, supported in both [[C Sharp (programming language)|C#]] 2.0 and [[Visual Basic .NET|Visual Basic 2005]]. [[WinRT]] also supports partial classes. <ref>{{Cite web |last=BillWagner |date=2024-11-14 |title=Partial Classes and Methods - C# |url=https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/partial-classes-and-methods |access-date=2025-02-06 |website=learn.microsoft.com |language=en-us}}</ref>
 
===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''.
<ref>{{cite web |url=http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.100).aspx |title=Static Classes and Static Class Members (C# Programming Guide) |work=C# Programming Guide |publisher=Microsoft |access-date=2012-05-08}}
</ref>
 
===Unnamed===
 
An ''unnamed class'' or ''anonymous class'' is not bound to a name or identifier upon definition.<ref>{{Cite web|title=Anonymous Classes (The Java Tutorials > Learning the Java Language > Classes and Objects)|url=https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html|access-date=2021-05-13|website=docs.oracle.com}}</ref><ref>{{Cite web|title=PHP: Anonymous classes - Manual|url=https://www.php.net/manual/en/language.oop5.anonymous.php|access-date=2021-08-11|website=www.php.net}}</ref> This is analogous to named versus [[anonymous function|unnamed functions]].
 
== Benefits ==
The benefits of organizing software into object classes fall into three categories:<ref>{{cite web|title=What is an Object?|url=http://docs.oracle.com/javase/tutorial/java/concepts/object.html|work=oracle.com|publisher=Oracle Corporation|access-date=13 December 2013}}</ref>
 
* 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.<ref>{{cite book|last=Booch|first=Grady|title=Object-Oriented Analysis and Design with Applications|publisher=Addison-Wesley Professional|isbn=978-0-201-89551-3|pages=1–28|url=http://my.safaribooksonline.com/book/software-engineering-and-development/object/9780201895513|author2=Robert A. Maksimchuk |author3=Michael W. Engle |author4=Bobbi J. Young Ph.D. |author5=Jim Conallen |author6= Kelli A. Houston |access-date=20 December 2013|date=April 30, 2007|quote=There are fundamental limiting factors of human cognition; we can address these constraints through the use of decomposition, abstraction, and hierarchy.}}</ref>
 
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 reuse 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 tailoring 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.<ref>{{cite book|last=Jacobsen|first=Ivar|title=Object Oriented Software Engineering|year=1992|publisher=Addison-Wesley ACM Press|isbn=0-201-54435-0|author2=Magnus Christerson|author3=Patrik Jonsson|author4=Gunnar Overgaard|url=https://archive.org/details/objectorientedso00jaco}}</ref>
 
== Runtime representation ==
{{Citations needed|Runtime representation|date=May 2024}}
As a data type, a class is usually considered as a compile time construct.<ref>{{cite web |title=C++ International standard |url=http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4713.pdf |archive-url=https://web.archive.org/web/20171209100334/http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2017/n4713.pdf |archive-date=2017-12-09 |url-status=live |website=Working Draft, Standard for Programming Language C++ |publisher=ISO/IEC JTC1/SC22 WG21 |access-date=5 January 2020}}</ref> A language or library may also support [[Prototype-based programming|prototype]] or [[Factory method pattern|factory]] [[metaobject]]s that represent runtime information about classes, or even represent metadata that provides access to [[reflective programming]] (reflection) facilities and ability to manipulate data structure formats at runtime. 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 runtime. Some dynamic languages do not make strict distinctions between runtime 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]].
 
==Prototype-based programming==
 
In contrast to creating an object from a class, some programming contexts support object creation by copying (cloning) a [[prototype-based programming|prototype]] object.<ref>{{Cite web |last=Amir |first=Masroor |title=OOP - Object Oriented Programming - Concepts {{!}} Languages {{!}} Benefits [2023] |url=https://www.thegeeksbot.com/2023/03/object-oriented-programming.html |access-date=2023-04-04 |website=The Geeks Bot {{!}} A Computer Science Site for geeks |date=25 March 2023 |language=en}}</ref>
 
== See also ==
{{Portal|Computer programming}}
* {{Annotated link|Class diagram}}
* {{Annotated link|Class variable}}
* {{Annotated link|Instance variable}}
* {{Annotated link|List of object-oriented programming languages}}
* {{Annotated link|Trait (computer programming)}}
 
== Notes ==
{{Notelist}}
{{Reflist|30em}}
 
== References ==
{{Refbegin}}
* {{cite book |last=Booch |first=Grady |year=1994 |title=Objects and Design with Applications, Second Edition |publisher=Benjamin/Cummings}}
* {{cite book |last1=Gamma |last2=Helm |last3=Johnson |last4=Vlissides |year=1995 |title=Design Patterns: Elements of Reusable Object-Oriented Software |url=https://archive.org/details/designpatternsel00gamm |url-access=registration |publisher=Addison Wesley |isbn=9780201633610}}
* {{cite book |isbn=978-0-262-02523-2 |title=Foundations of Object-Oriented Languages: Types and Semantics |last=Bruce |first=Kim B. |year=2002 |publisher=MIT Press |___location=Cambridge, Massachusetts |url=http://mitpress.mit.edu/books/foundations-object-oriented-languages}}
{{Refend}}
 
== Further reading ==
* [http://lucacardelli.name/TheoryOfObjects.html Abadi; Cardelli: A Theory of Objects]
* [http://www.open-std.org/jtc1/sc22/wg21/ ISO/IEC 14882:2003 Programming Language C++, International standard]
* [http://www.laputan.org/reflection/warfare.html Class Warfare: Classes vs. Prototypes], by Brian Foote
* Meyer, B.: "Object-oriented software construction", 2nd edition, Prentice Hall, 1997, {{ISBN|0-13-629155-4}}
* Rumbaugh et al.: "Object-oriented modeling and design", Prentice Hall, 1991, {{ISBN|0-13-630054-5}}
 
{{Types of programming languages}}
{{Data types}}
 
{{DEFAULTSORT:Class (Computer Programming)}}
[[Category:Class (computer programming)| ]]
[[Category:Programming constructs]]
[[Category:Programming language topics]]