Class (programming): Difference between revisions
imported>Xqbot m Bot: Fixing double redirect to Class (computer programming) |
imported>QuantumNinus |
||
| Line 1: | Line 1: | ||
# | {{Short description|Syntactic specification of an object}} | ||
In [[Computer programming|programming]], a '''class''' is a [[ Syntax (programming languages) | syntactic]] [[entity]] structure used to create [[Object (computer science)|objects]].<ref name="CommonBase">{{ | |||
cite report | |||
|last1=Dahl | |||
|first1=Ole-Johan |author-link=Ole-Johan Dahl | |||
|last2=Myhrhaug |first2=Bjørn | |||
|last3=Nygaard |first3=Kristen |author3-link=Kristen Nygaard | |||
|date=1970 | |||
|url=http://www.edelweb.fr/Simula/#7 | |||
|title=Common Base Language | |||
|publisher=Norwegian Computing Center | |||
|access-date=20 August 2025 | |||
|url-status=usurped | |||
|archive-url=https://web.archive.org/web/20240919044713/https://www.softwarepreservation.org/projects/ALGOL/manual/Simula-CommonBaseLanguage.pdf | |||
|archive-date=2024-09-19 | |||
}}</ref>{{rp| 1.3.3}} 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}}}} | |||
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. | |||
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''. | |||
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>, which is called a [[top type]]. | |||
== History == | |||
The concept was primarily introduced in the OOP by the [[Simula]] language in 1960's and continuously being used by a large of object-oriented programming languages.<ref name="CommonBase" />{{rp| 1.3.3}} Its creation was based in similar concept as [[Block (programming)|block]] used in previous-based [[Algol]] programming language.<ref name="CommonBase" />{{rp| 1.3.2}} | |||
==Attributes== | |||
===Object lifecycle=== | |||
{{Main|Object lifetime}} | |||
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. | |||
Most languages allow for custom logic at lifecycle events via a [[Constructor (object-oriented programming)|constructor]] and a [[Destructor (computer programming)|destructor]]. | |||
===Type=== | |||
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 |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. | |||
=== <span class="anchor" id="PROPERTY"></span>Structure === | |||
[[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]] syntactically described (or ''[[property (programming)|properties]]'', ''[[field (computer science)|fields]]'', ''data [[member variable|members]]'', or ''[[attribute (computing)|attributes]]'').<ref name="CommonBase"/> 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> | |||
Some programming languages such as Eiffel support specification of [[class invariant|invariant]]s as part of the definition of the class, and enforce them through the type system. [[Encapsulation (object-oriented programming)|Encapsulation]] of state is necessary for being able to enforce the invariants of the class. | |||
=== Behavior === | |||
{{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 (or action<ref name="CommonBase"/>) 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> | |||
=== Interface === | |||
{{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. | |||
Languages that support class inheritance also allow classes to inherit interfaces from the classes that they are derived from. | |||
For example, if "<code>class Z</code>" inherits from "<code>class Y</code>" and if "<code>class Y</code>" implements the interface "<code>interface X</code>" then "<code>class Z</code>" also implements the functionality(constants and methods declaration) provided by "<code>interface X</code>". | |||
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. | |||
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> | |||
; Interface 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 color, 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 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. | |||
=== Member accessibility === | |||
{{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> | |||
* ''Private'' (or ''class-private'') restricts 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,<!-- {{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. | |||
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. | |||
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> | |||
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> | |||
{{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 feature other accessibility schemes: | |||
* ''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> | |||
* ''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> | |||
* ''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 {{mono|.jar}} file, yet still be in the same logical path as far as the JVM is concerned.<ref name=JavaAccessControl/> | |||
====Inheritance==== | |||
{{Main|Inheritance (object-oriented programming)|Inheritance (object-oriented programming)#Subclasses and superclasses}} | |||
Conceptually, a superclass is a [[superset]] of its subclasses. For example, {{code|GraphicObject}} could be a superclass of {{code|Rectangle}} and {{code|Ellipse}}, while {{code|Square}} would be a subclass of {{code|Rectangle}}. These are all [[Subset|subset relations]] in set theory as well, i.e., all squares are rectangles but not all rectangles are squares. | |||
A common conceptual error is to mistake a ''part of'' relation with a subclass. For example, a car and truck are both kinds of vehicles and it would be appropriate to model them as subclasses of a vehicle class. However, it would be an error to model the 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. | |||
In [[object-oriented modeling]] these kinds of relations are typically modeled as object properties. In this example, the {{code|Car}} class would have a property called {{code|parts}}. {{code|parts}} would be typed to hold a collection of objects, such as instances of {{code|Body}}, {{code|Engine}}, {{code|Tires}}, etc. | |||
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> | |||
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> | |||
Most modern object-oriented languages such as Smalltalk and Java require single inheritance at run time. For these languages, multiple inheritance may be useful for modeling but not for an implementation. | |||
However, [[semantic web]] application objects do have multiple superclasses. The volatility of the Internet requires this level of flexibility and the technology standards such as the [[Web Ontology Language|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 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> | |||
Although many class-based languages support inheritance, inheritance is not an intrinsic aspect of classes.{{Dubious|date=November 2025}}{{Non sequitur|date=November 2025}} 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]]). --> | |||
== Inter-class relationships == | |||
A programming language may support various class relationship features. | |||
=== Compositional === | |||
Classes can be composed of other classes, thereby establishing a compositional relationship between the enclosing class and its embedded classes. Compositional relationship between classes is also commonly known as a ''[[has-a]]'' relationship.{{sfn|Booch|1994|p=180}} For example, a class <code>Car</code> could be composed of and contain a class <code>Engine</code>. Therefore, a <code>Car</code> ''has an'' <code>Engine</code>. 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: | |||
<syntaxhighlight lang="objc"> | |||
@interface Car : NSObject | |||
@property NSString *name; | |||
@property Engine *engine | |||
@property NSArray *tires; | |||
@end | |||
</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). | |||
=== 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 ''{{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. | |||
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. | |||
Example (Simplified Objective-C 2.0 code, from iPhone SDK): | |||
<syntaxhighlight lang="objc"> | |||
@interface UIResponder : NSObject //... | |||
@interface UIView : UIResponder //... | |||
@interface UIScrollView : UIView //... | |||
@interface UITableView : UIScrollView //... | |||
</syntaxhighlight> | |||
In this example, a UITableView ''is a'' UIScrollView ''is a'' UIView ''is a'' UIResponder ''is an'' NSObject. | |||
===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 {{anchor|Abstract|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 <code>abstract</code> 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> | |||
===Final{{anchor|Final}}=== | |||
<span class="anchor" id="Non-subclassable"></span><span class="anchor" id="Sealed"></span> | |||
A '''final class''' cannot be subclassed. It is basically the opposite of an abstract class, which must be subclassed to be used and cannot be [[Instance (computer science)|instantiated]] directly. A final class is implicitly a concrete class, {{em|can}} be instantiated directly. | |||
A class is declared as final via the keyword {{code|final|lang=java}} in Java, C++ or PHP, or {{code|sealed|lang=csharp}} in C#. 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> | |||
Final 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> --> | |||
===Sealed=== | |||
A "sealed class" is a class that restricts inheritance to a selected list of classes. It should not be confused with the <code>sealed</code> keyword in C#, which denotes a final class. The list of permitted classes the sealed class may inherit is specified using a "permits" clause.<ref>{{Cite web|title=Sealed Classes|url=https://docs.oracle.com/en/java/javase/25/language/sealed-classes-and-interfaces.html|website=docs.oracle.com|access-date=16 October 2025|publisher=Oracle Help Center}}</ref> | |||
<syntaxhighlight lang="Java"> | |||
public sealed class Quadrilateral | |||
extends Shape | |||
implements Renderable, Transformable, Comparable<Quadrilateral>, Measurable | |||
permits Parallelogram, Trapezoid, Kite { | |||
// ... | |||
} | |||
</syntaxhighlight> | |||
<code>non-sealed</code> is another keyword used to declare that a class or interface which extends a sealed class can be extended by unknown classes. | |||
===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]]. | |||
== Class-based programming == | |||
{{Short description|Programming which all objects are created by classes}} | |||
{{hatnote|Content from [[Class-based programming]] was merged into this article following talk page consensus. See [[Talk:Class-based_programming#Merger_proposal_(2008)]]}} | |||
'''Class-based programming''', or more commonly '''class-orientated''', is a style of [[object-oriented programming]] which all [[object (computer science)|object]]s are created by a [[class (programming)|class]] and without [[inheritance (object-oriented programming)|inheritance]] between them.<ref>https://dl.acm.org/doi/pdf/10.1145/38765.38823</ref><ref name="CLU's history">https://dl.acm.org/doi/pdf/10.1145/234286.1057826</ref> | |||
The most popular and developed model of OOP is a class-based model, instead of an object-based model. In this model, objects are entities that combine ''[[state (computer science)|state]]'' (i.e., data), ''[[behavior]]'' (i.e., procedures, or ''[[method (computer science)|method]]s'') and ''[[identity (object-oriented programming)|identity]]'' (unique existence among all other objects). The structure and behavior of an object are defined by a [[Class (programming)|class]], which is a [[syntactic]] structure, or [[blueprint]], of all objects of a specific type. An object must be explicitly created based on a class and an object thus created is considered to be an [[instantiation (computer science)|instance]] of that class. An object is similar to a [[data structure|structure]], with the addition of method pointers, member access control, and an implicit data member which locates instances of the class (i.e., objects of the class) in the class hierarchy (essential for runtime inheritance features). | |||
=== Encapsulation === | |||
[[Information hiding|Encapsulation]] prevents users from breaking the [[Invariant (computer science)|invariants]] of the class, which is useful because it allows the implementation of a class of objects to be changed for aspects not exposed in the interface without impact to user code. The definitions of encapsulation focus on the grouping and packaging of related information ([[cohesion (computer science)|cohesion]]) rather than security issues. | |||
=== Critique === | |||
Class-based languages, or, to be more precise, [[typed language]]s, where [[Subclass (computer science)|subclassing]] is the only way of [[subtyping]], have been criticized for mixing up implementations and interfaces—the essential principle in object-oriented programming. The critics say one might create a bag class that stores a [[Collection class|collection]] of objects, then extend it to make a new class called a set class where the duplication of objects is eliminated.<ref>{{cite web|first=Oleg|last=Kiselyov|title=Subtyping, Subclassing, and Trouble with OOP|url=http://okmij.org/ftp/Computation/Subtyping/|access-date=7 October 2012}}</ref><ref>{{cite web|title=A set cannot be a subtype of a bag|last=Ducasse|first=Stéphane|url=http://stephane.ducasse.free.fr/Resources/LecturesInPowerpoint/STOOP-416-LSP.ppt|access-date=7 October 2012}}</ref> Now, a function that takes an object of the bag class may expect that adding two objects increases the size of a bag by two, yet if one passes an object of a set class, then adding two objects may or may not increase the size of a bag by two. The problem arises precisely because subclassing implies subtyping even in the instances where the principle of subtyping, known as the [[Liskov substitution principle]], does not hold. [[Barbara Liskov]] and [[Jeannette Wing]] formulated the principle succinctly in a 1994 paper as follows: | |||
<!-- inline math as LaTeX has poor baseline alignment (better with MathJaX HTML/CSS rendering of LaTeX) | |||
:''Let <math>q(x)</math> be a property provable about objects <math>x</math> of type <math>T</math>. Then <math>q(y)</math> should be provable for objects <math>y</math> of type <math>S</math>, where <math>S</math> is a subtype of <math>T</math>.'' | |||
--><!-- inline math as HTML --> | |||
<blockquote>''Subtype Requirement'': Let {{tmath| \phi(x) }} be a property provable about objects {{tmath| x }} of type {{tmath| T}}. Then {{tmath| \phi(y) }} should be true for objects {{tmath| y }} of type {{tmath| S }} where {{tmath| S }} is a subtype of {{tmath| T}}. </blockquote> | |||
<!-- inline math as HTML bold | |||
:''Let {{math| '''q(x)''' }} be a property provable about objects {{math| '''x''' }} of type {{math| '''T'''. }} Then {{math| '''q(y)''' }} should be provable for objects {{math| '''y''' }} of type {{math| '''S''', }} where {{math| '''S''' }} is a subtype of {{math| '''T'''. }}'' | |||
--> | |||
Thus, normally one must distinguish subtyping and subclassing. Most current object-oriented languages distinguish subtyping and subclassing, however some approaches to design do not. | |||
Also, another common example is that a person object created from a [[Subclass (computer science)|child class]] cannot become an object of [[parent class]] because a child class and a parent class inherit a person class but class-based languages mostly do not allow to change the kind of class of the object at runtime. For class-based languages, this restriction is essential in order to preserve unified view of the class to its users. The users should not need to care whether one of the implementations of a method happens to cause changes that break the [[Invariant (computer science)|invariants]] of the class. Such changes can be made by destroying the object and constructing another in its place. Polymorphism can be used to preserve the relevant interfaces even when such changes are done, because the objects are viewed as black box abstractions and accessed via object [[identity (object-oriented programming)|identity]]. However, usually the value of object references referring to the object is changed, which causes effects to client code. | |||
=== Example languages === | |||
{{Category see also|Class-based programming languages}} | |||
Although [[Simula]] introduced the class abstraction, the canonical example of a class-based language is [[Smalltalk]]. Others include [[PHP]], [[C++]], [[Java (programming language)|Java]], [[C Sharp (programming language)|C#]], and [[Objective-C]]. | |||
{{Dubious|date=November 2025}}{{Non sequitur|date=November 2025}} | |||
==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 == | |||
{{columns list| | |||
* {{Annotated link|Block (programming)}} | |||
* {{Annotated link|Class diagram}} | |||
* {{Annotated link|Class invariant}} | |||
* {{Annotated link|Class variable}} | |||
* {{Annotated link|Function (computer science)}} | |||
* {{Annotated link|Instance variable}} | |||
* {{Annotated link|Metaclass}} | |||
* {{Annotated link|Object (computer science)}} | |||
* {{Annotated link|Syntax (programming language)}} | |||
* {{Annotated link|Variable (computer science)}} | |||
}} | |||
{{Portal|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}} | |||
{{Programming paradigms navbox}} | |||
{{Types of programming languages}} | |||
{{DEFAULTSORT:Class (Computer Programming)}} | |||
[[Category:Class (computer programming)| ]] | |||
[[Category:Programming constructs]] | |||
[[Category:Programming language topics]] | |||
Latest revision as of 22:18, 15 November 2025
In programming, a class is a syntactic entity structure used to create objects.[1]Template:Rp The capabilities of a class differ between programming languages, but generally the shared aspects consist of state (variables) and behavior (methods) that are each either associated with a particular object or with all objects of that class.Template:SfnTemplate:Sfn
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.
If the language supports 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.
In purely object-oriented programming languages, such as Java and C#, all classes might be part of an inheritance tree such that the root class is Object, meaning all objects instances are of Object or implicitly extend Object, which is called a top type.
History
The concept was primarily introduced in the OOP by the Simula language in 1960's and continuously being used by a large of object-oriented programming languages.[1]Template:Rp Its creation was based in similar concept as block used in previous-based Algol programming language.[1]Template:Rp
Attributes
Object lifecycle
Script error: No such module "Labelled list hatnote".
As an 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 to the object is provided to consuming code. The object is usable until it is destroyed Template:Endash its state memory is de-allocated.
Most languages allow for custom logic at lifecycle events via a constructor and a destructor.
Type
An object expresses data type as an interface Template: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.Template:Sfn In the terms of type theory, a class is an implementationTemplate:Mdashba concrete data structure and collection of subroutinesTemplate:Mdashbwhile a type is an interface. Different (concrete) classes can produce objects of the same (abstract) type (depending on type system). For example, the type (interface) Template:Mono might be implemented by Template:Mono that is fast for small stacks but scales poorly and Template:Mono that scales well but has high overhead for small stacks.
Structure
A class contains data field syntactically described (or properties, fields, data members, or attributes).[1] These are usually field types and names that will be associated with state variables at program run time; these state variables either belong to the class or specific instances of the class. In most languages, the structure defined by the class determines the layout of the memory used by its instances. Other implementations are possible: for example, objects in Python use associative key-value containers.[2]
Some programming languages such as Eiffel support specification of invariants as part of the definition of the class, and enforce them through the type system. Encapsulation of state is necessary for being able to enforce the invariants of the class.
Behavior
Script error: No such module "Labelled list hatnote".
The behavior (or action[1]) of a class or its instances is defined using methods. Methods are subroutines with the ability to operate on objects or classes. These operations may alter the state of an object or simply provide ways of accessing it.Template:Sfn 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.[3][4]
Interface
Script error: No such module "Labelled list hatnote". Script error: No such module "labelled list hatnote".
Every class implements (or realizes) an interface by providing structure and behavior. Structure consists of data and state, and behavior consists of code that specifies how methods are implemented.Template:Sfn There is a distinction between the definition of an interface and the implementation of that interface; however, this line is blurred in many programming languages because class declarations both define and implement an interface. Some languages, however, provide features that separate interface and implementation. For example, an abstract class can define an interface without providing an implementation.
Languages that support class inheritance also allow classes to inherit interfaces from the classes that they are derived from.
For example, if "class Z" inherits from "class Y" and if "class Y" implements the interface "interface X" then "class Z" also implements the functionality(constants and methods declaration) provided by "interface X".
In languages that support access specifiers, the interface of a class is considered to be the set of public members of the class, including both methods and attributes (via implicit getter and setter methods); any private members or internal data structures are not intended to be depended on by external code and thus are not part of the interface.
Object-oriented programming methodology dictates that the operations of any interface of a class are to be independent of each other. It results in a layered design where clients of an interface use the methods declared in the interface. An interface places no requirements for clients to invoke the operations of one interface in any particular order. This approach has the benefit that client code can assume that the operations of an interface are available for use whenever the client has access to the object.[5]
- Interface 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 color, 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 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.
Member accessibility
Script error: No such module "redirect hatnote". Script error: No such module "labelled list hatnote".
The following is a common set of access specifiers:[6]
- Private (or class-private) restricts access to the class itself. Only methods that are part of the same class can access private members.
- Protected (or class-protected) allows the class itself and all its subclasses to access the member.
- Public means that any code can access the member by its name.
Although many object-oriented languages support the above access specifiers, their semantics may differ.
Object-oriented design uses the access specifiers in conjunction with careful design of public method implementations to enforce class invariants—constraints on the state of the objects. A common usage of access specifiers is to separate the internal data of a class from its interface: the internal structure is made private, while public accessor methods can be used to inspect or alter such private data.
Access specifiers do not necessarily control visibility, in that even private members may be visible to client external code. In some languages, an inaccessible but visible member may be referred to at 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.[7]
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. For example, the Java language does not allow client code that accesses the private data of a class to compile.[8] 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.[9]
Some languages feature other accessibility schemes:
- Instance vs. class accessibility: Ruby supports instance-private and instance-protected access specifiers in lieu of class-private and class-protected, respectively. They differ in that they restrict access based on the instance itself, rather than the instance's class.[10]
- 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.[11]
- Path-based: Java supports restricting access to a member within a Java package, which is the logical path of the file. However, it is a common practice when extending a Java framework to implement classes in the same package as a framework class to access protected members. The source file may exist in a completely different location, and may be deployed to a different Template:Mono file, yet still be in the same logical path as far as the JVM is concerned.[6]
Inheritance
Script error: No such module "Labelled list hatnote".
Conceptually, a superclass is a superset of its subclasses. For example, GraphicObject could be a superclass of Rectangle and Ellipse, while Square would be a subclass of Rectangle. These are all subset relations in set theory as well, i.e., all squares are rectangles but not all rectangles are squares.
A common conceptual error is to mistake a part of relation with a subclass. For example, a car and truck are both kinds of vehicles and it would be appropriate to model them as subclasses of a vehicle class. However, it would be an error to model the 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.
In object-oriented modeling these kinds of relations are typically modeled as object properties. In this example, the Car class would have a property called parts. parts would be typed to hold a collection of objects, such as instances of Body, Engine, Tires, etc.
Object modeling languages such as UML include capabilities to model various aspects of "part of" and other kinds of relations – data such as the cardinality of the objects, constraints on input and output values, etc. This information can be utilized by developer tools to generate additional code besides the basic data definitions for the objects, such as error checking on get and set methods.[12]
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.[13]
Most modern object-oriented languages such as Smalltalk and Java require single inheritance at run time. For these languages, multiple inheritance may be useful for modeling but not for an implementation.
However, semantic web application objects do have multiple superclasses. The volatility of the Internet requires this level of flexibility and the technology standards such as the Web Ontology Language (OWL) are designed to support it.
A similar issue is whether or not the class hierarchy can be modified at run time. Languages such as Flavors, CLOS, and Smalltalk all support this feature as part of their meta-object protocols. Since classes are themselves first-class objects, it is possible to have them dynamically alter their structure by sending them the appropriate messages. Other languages that focus more on strong typing such as Java and C++ do not allow the class hierarchy to be modified at run time. Semantic web objects have the capability for run time changes to classes. The 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.[14]
Although many class-based languages support inheritance, inheritance is not an intrinsic aspect of classes.Script error: No such module "Unsubst".Template:Non sequitur An object-based language (i.e. Classic Visual Basic) supports classes yet does not support inheritance.
Inter-class relationships
A programming language may support various class relationship features.
Compositional
Classes can be composed of other classes, thereby establishing a compositional relationship between the enclosing class and its embedded classes. Compositional relationship between classes is also commonly known as a has-a relationship.Template:Sfn 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.Template:Sfn For example, in Objective-C 2.0:
@interface Car : NSObject
@property NSString *name;
@property Engine *engine
@property NSArray *tires;
@end
This Template:Mono class has an instance of Template:Mono (a string object), Template:Mono, and Template:Mono (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 Template:Vanchor) 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.Template:Sfn 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.[15] If multiple inheritance is allowed, the hierarchy is a directed acyclic graph (or DAG for short), otherwise it is a tree. The hierarchy has classes as nodes and inheritance relationships as links. Classes in the same level are more likely to be associated than classes in different levels. The levels of this hierarchy are called layers or levels of abstraction.
Example (Simplified Objective-C 2.0 code, from iPhone SDK):
@interface UIResponder : NSObject //...
@interface UIView : UIResponder //...
@interface UIScrollView : UIView //...
@interface UITableView : UIScrollView //...
In this example, a UITableView is a UIScrollView is a UIView is a UIResponder is an NSObject.
Modeling
In object-oriented analysis and in Unified Modelling Language (UML), an association between two classes represents a collaboration between the classes or their corresponding instances. Associations have direction; for example, a bi-directional association between two classes indicates that both of the classes are aware of their relationship.[16] Associations may be labeled according to their name or purpose.Template:Sfn
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.[16]
Taxonomy
There are many categories of classes, some of which overlap.
Abstract and concrete Script error: No such module "anchor".
Script error: No such module "Labelled list hatnote".
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 Template:Em be directly instantiated. Instantiation of an abstract class can occur only indirectly, via a concrete Template:Emclass.
An abstract class is either labeled as such explicitly or it may simply specify abstract methods (or virtual methods). An abstract class may provide implementations of some methods, and may also specify virtual methods via signatures that are to be implemented by direct or indirect descendants of the abstract class. Before a class derived from an abstract class can be instantiated, all abstract methods of its parent classes must be implemented by some class in the derivation chain.[17]
Most object-oriented programming languages allow the programmer to specify which classes are considered abstract and will not allow these to be instantiated. For example, in Java, C# and PHP, the keyword abstract is used.[18][19] 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).[17]
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.[9] Other languages, notably Java and C#, support a variant of abstract classes called an interface via a keyword in the language. In these languages, multiple inheritance is not allowed, but a class can implement multiple interfaces. Such a class can only contain abstract publicly accessible methods.[15][20][21]
Local and inner
In some languages, classes can be declared in scopes other than the global scope. There are various types of such classes.
An inner class is a class defined within another class. The relationship between an inner class and its containing class can also be treated as another type of class association. An inner class is typically neither associated with instances of the enclosing class nor instantiated along with its enclosing class. Depending on 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).[22][23]
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 variables declared within its enclosing function, but may not access the function's automatic variables.[24]
Metaclass
Script error: No such module "Labelled list hatnote".
A metaclass is a class where instances are classes.Template:Sfn A metaclass describes a common structure of a collection of classes and can implement a design pattern or describe particular kinds of classes. Metaclasses are often used to describe frameworks.[25]
In some languages, such as Python, Ruby or Smalltalk, a class is also an object; thus each class is an instance of a unique metaclass that is built into the language.[2][26] Template:Sfn The Common Lisp Object System (CLOS) provides metaobject protocols (MOPs) to implement those classes and metaclasses.[27]
FinalScript error: No such module "anchor".
A final class cannot be subclassed. It is basically the opposite of an abstract class, which must be subclassed to be used and cannot be instantiated directly. A final class is implicitly a concrete class, Template:Em be instantiated directly.
A class is declared as final via the keyword final in Java, C++ or PHP, or sealed in C#. However, this concept should not be confused with classes in Java qualified with the keyword sealed, that only allow inheritance from selected subclasses.[28][29][30][31]
For example, Java's Template:Java class is marked as final.[32]
Final classes may allow a compiler to perform optimizations that are not available for classes that can be subclassed.[33]
Sealed
A "sealed class" is a class that restricts inheritance to a selected list of classes. It should not be confused with the sealed keyword in C#, which denotes a final class. The list of permitted classes the sealed class may inherit is specified using a "permits" clause.[34]
public sealed class Quadrilateral
extends Shape
implements Renderable, Transformable, Comparable<Quadrilateral>, Measurable
permits Parallelogram, Trapezoid, Kite {
// ...
}
non-sealed is another keyword used to declare that a class or interface which extends a sealed class can be extended by unknown classes.
Open
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, all classes are open. In Python, classes can be created at runtime, and all can be modified afterward.[35] 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 mixins, though, in any language with multiple inheritance, a mixin is simply a class that does not represent an is-a-type-of relationship. Mixins are typically used to add the same methods to multiple classes; for example, a class Template:Mono might provide a method called Template:Mono when included in classes Template:Mono and Template:Mono that do not share a common parent.
Partial
In languages supporting the feature, a partial class is a class whose definition may be split into multiple pieces, within a single source-code file or across multiple files.[36] 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 code generators, such as visual designers.[36] 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.[37]
Other benefits and effects of the partial class feature include:
- Enables separation of a class's interface and implementation code in a unique way.
- Eases navigation through large classes within an editor.
- Enables separation of concerns, in a way similar to aspect-oriented programming but without using any extra tools.
- Enables multiple developers to work on a single class concurrently without the need to merge individual code into one file at a later time.
Partial classes have existed in Smalltalk under the name of Class Extensions for considerable time. With the arrival of the .NET framework 2, Microsoft introduced partial classes, supported in both C# 2.0 and Visual Basic 2005. WinRT also supports partial classes.[38]
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. [39]
Unnamed
An unnamed class or anonymous class is not bound to a name or identifier upon definition.[40][41] This is analogous to named versus unnamed functions.
Benefits
The benefits of organizing software into object classes fall into three categories:[42]
- 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.[43]
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.[44]
Runtime representation
Template:Citations needed As a data type, a class is usually considered as a compile time construct.[45] A language or library may also support prototype or factory metaobjects 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.
Class-based programming
Script error: No such module "Hatnote".
Class-based programming, or more commonly class-orientated, is a style of object-oriented programming which all objects are created by a class and without inheritance between them.[46][47]
The most popular and developed model of OOP is a class-based model, instead of an object-based model. In this model, objects are entities that combine state (i.e., data), behavior (i.e., procedures, or methods) and identity (unique existence among all other objects). The structure and behavior of an object are defined by a class, which is a syntactic structure, or blueprint, of all objects of a specific type. An object must be explicitly created based on a class and an object thus created is considered to be an instance of that class. An object is similar to a structure, with the addition of method pointers, member access control, and an implicit data member which locates instances of the class (i.e., objects of the class) in the class hierarchy (essential for runtime inheritance features).
Encapsulation
Encapsulation prevents users from breaking the invariants of the class, which is useful because it allows the implementation of a class of objects to be changed for aspects not exposed in the interface without impact to user code. The definitions of encapsulation focus on the grouping and packaging of related information (cohesion) rather than security issues.
Critique
Class-based languages, or, to be more precise, typed languages, where subclassing is the only way of subtyping, have been criticized for mixing up implementations and interfaces—the essential principle in object-oriented programming. The critics say one might create a bag class that stores a collection of objects, then extend it to make a new class called a set class where the duplication of objects is eliminated.[48][49] Now, a function that takes an object of the bag class may expect that adding two objects increases the size of a bag by two, yet if one passes an object of a set class, then adding two objects may or may not increase the size of a bag by two. The problem arises precisely because subclassing implies subtyping even in the instances where the principle of subtyping, known as the Liskov substitution principle, does not hold. Barbara Liskov and Jeannette Wing formulated the principle succinctly in a 1994 paper as follows:
Subtype Requirement: Let Template:Tmath be a property provable about objects Template:Tmath of type Template:Tmath. Then Template:Tmath should be true for objects Template:Tmath of type Template:Tmath where Template:Tmath is a subtype of Template:Tmath.
Thus, normally one must distinguish subtyping and subclassing. Most current object-oriented languages distinguish subtyping and subclassing, however some approaches to design do not.
Also, another common example is that a person object created from a child class cannot become an object of parent class because a child class and a parent class inherit a person class but class-based languages mostly do not allow to change the kind of class of the object at runtime. For class-based languages, this restriction is essential in order to preserve unified view of the class to its users. The users should not need to care whether one of the implementations of a method happens to cause changes that break the invariants of the class. Such changes can be made by destroying the object and constructing another in its place. Polymorphism can be used to preserve the relevant interfaces even when such changes are done, because the objects are viewed as black box abstractions and accessed via object identity. However, usually the value of object references referring to the object is changed, which causes effects to client code.
Example languages
Script error: No such module "Category see also".Template:Category see also/Category pair check Although Simula introduced the class abstraction, the canonical example of a class-based language is Smalltalk. Others include PHP, C++, Java, C#, and Objective-C.
Script error: No such module "Unsubst".Template:Non sequitur
Prototype-based programming
In contrast to creating an object from a class, some programming contexts support object creation by copying (cloning) a prototype object.[50]
See also
Template:Columns list Script error: No such module "Portal".
Notes
Template:Notelist Template:Reflist
References
- Script error: No such module "citation/CS1".
- Script error: No such module "citation/CS1".
- Script error: No such module "citation/CS1".
Further reading
- Abadi; Cardelli: A Theory of Objects
- ISO/IEC 14882:2003 Programming Language C++, International standard
- Class Warfare: Classes vs. Prototypes, by Brian Foote
- Meyer, B.: "Object-oriented software construction", 2nd edition, Prentice Hall, 1997, Template:ISBN
- Rumbaugh et al.: "Object-oriented modeling and design", Prentice Hall, 1991, Template:ISBN
Template:Programming paradigms navbox Template:Types of programming languages
- ↑ a b c d e Template:Cite report
- ↑ a b Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ a b Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ a b Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ a b Script error: No such module "citation/CS1".
- ↑ a b Script error: No such module "citation/CS1".
- ↑ a b Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ a b Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ https://dl.acm.org/doi/pdf/10.1145/38765.38823
- ↑ https://dl.acm.org/doi/pdf/10.1145/234286.1057826
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".
- ↑ Script error: No such module "citation/CS1".