Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Class (computer programming)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Short description|Specification of an object}} In [[object-oriented programming]], a '''class''' defines the shared aspects of [[Object (computer science)|objects]] created from the class. The capabilities of a class differ between [[programming language]]s, but generally the shared aspects consist of state ([[Variable (computer science)|variables]]) and behavior ([[Method (computer programming)|methods]]) that are each either associated with a particular object or with all objects of that class.{{sfn|Gamma|Helm|Johnson|Vlissides|1995|p=14}}{{sfn|Bruce|2002|loc=2.1 Objects, classes, and object types, {{Google books|9NGWq3K1RwUC|Objects, classes, and object types|page=18|plainurl=yes}}}} 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''. ==Attributes== ===Object lifecycle=== 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 (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.png|frame|right|[[Unified Modeling Language|UML]] notation for classes]] A class contains [[Data (computing)|data]] [[Field (computer science)|field]] descriptions (or ''[[property (programming)|properties]]'', ''[[field (computer science)|fields]]'', ''data [[member variable|members]]'', or ''[[attribute (computing)|attributes]]''). These are usually field types and names that will be associated with state variables at program run time; these state variables either belong to the class or specific instances of the class. In most languages, the structure defined by the class determines the layout of the memory used by its instances. Other implementations are possible: for example, objects in [[Python (programming language)|Python]] use associative key-value containers.<ref name="pythondata model">{{cite web|url=https://docs.python.org/reference/datamodel.html|title=3. Data model|work=The Python Language Reference|publisher=Python Software Foundation|access-date=2012-04-26}}</ref> 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 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> === Class 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 "class A" inherits from "class B" and if "class B" implements the interface "interface B" then "class A" also inherits the functionality(constants and methods declaration) provided by "interface B". In languages that support [[#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> ; Class 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 .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)|Superclass (computer science)|Subclass (computer science)}} Conceptually, a superclass is a [[superset]] of its subclasses. For example, {{Mono|GraphicObject}} could be a superclass of {{Mono|Rectangle}} and {{Mono|Ellipse}}, while {{Mono|Square}} would be a subclass of {{Mono|Rectangle}}. These are all [[Subset|subset relations]] in set theory as well, i.e., all squares are rectangles but not all rectangles are squares. 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 {{Mono|Car}} class would have a property called {{Mono|parts}}. {{Mono|parts}} would be typed to hold a collection of objects, such as instances of {{Mono|Body}}, {{Mono|Engine}}, {{Mono|Tires}}, etc. 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. 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 "Car" could be composed of and contain a class "Engine". Therefore, a Car ''has an'' Engine. One aspect of composition is containment, which is the enclosure of component instances by the instance that has them. If an enclosing object contains component instances by value, the components and their enclosing object have a similar [[Object lifetime|lifetime]]. If the components are contained by reference, they may not have a similar lifetime.{{sfn|Booch|1994|p=128-129}} For example, in Objective-C 2.0: <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=== <span class="anchor" id="Abstract_and_concrete_classes"></span><span class="anchor" id="Abstract_and_Concrete"></span> {{see also|Abstract type}} In a language that supports inheritance, an ''abstract class'', or ''abstract base class'' (''ABC''), is a class that cannot be directly instantiated. By contrast, a ''concrete class'' is a class that {{em|can}} be directly instantiated. Instantiation of an abstract class can occur only indirectly, via a concrete {{em|sub}}class. An abstract class is either labeled as such explicitly or it may simply specify ''[[abstract method]]s'' (or ''[[virtual method]]s''). An abstract class may provide implementations of some methods, and may also specify virtual methods via [[Type signature|signatures]] that are to be implemented by direct or indirect descendants of the abstract class. Before a class derived from an abstract class can be instantiated, all abstract methods of its parent classes must be implemented by some class in the derivation chain.<ref name="cpppoly">{{cite web|url=http://www.cplusplus.com/doc/tutorial/polymorphism/ |title=Polymorphism|work=C++ Language Tutorial|publisher=cplusplus.com|access-date=2012-05-02}}</ref> Most object-oriented programming languages allow the programmer to specify which classes are considered abstract and will not allow these to be instantiated. For example, in [[Java (programming language)|Java]], [[C Sharp (programming language)|C#]] and [[PHP]], the keyword ''abstract'' is used.<ref>{{cite web| url=http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html|title=Abstract Methods and Classes|work=The Java Tutorials|publisher=Oracle|access-date=2012-05-02}}</ref><ref>{{cite web|url=http://php.net/manual/en/language.oop5.abstract.php|title=Class Abstraction|work=PHP Manual|publisher=The PHP Group|access-date=2012-05-02}}</ref> In [[C++]], an abstract class is a class having at least one abstract method given by the appropriate syntax in that language (a pure virtual function in C++ parlance).<ref name=cpppoly/> A class consisting of only pure virtual methods is called a ''pure abstract base class'' (or ''pure ABC'') in C++ and is also known as an ''interface'' by users of the language.<ref name=cppinterface/> Other languages, notably Java and C#, support a variant of abstract classes called an [[Interface (Java)|interface]] via a keyword in the language. In these languages, [[multiple inheritance]] is not allowed, but a class can implement multiple interfaces. Such a class can only contain abstract publicly accessible methods.<ref name=javainterface/><ref>{{cite web |url=http://msdn.microsoft.com/en-us/library/ms173156.aspx |title=Interfaces (C# Programming Guide) |work=C# Programming Guide |publisher=Microsoft |access-date=2013-08-15}}</ref><ref> {{cite web |url=http://msdn.microsoft.com/en-us/library/ms173149.aspx |title=Inheritance (C# Programming Guide) |work=C# Programming Guide |publisher=Microsoft |access-date=2012-05-02}}</ref> <!--Abstract classes defined as interfaces are a much more specific use of the more general meaning of the term ''interface'', even as used in computer science, and the concept of interfaces has seen much use and popularity within the realm of languages that support object-orientation.--> ===Local and inner=== In some languages, classes can be declared in [[Scope (programming)|scopes]] other than the global scope. There are various types of such classes. An ''[[inner class]]'' is a class defined within another class. The relationship between an inner class and its containing class can also be treated as another type of class association. An inner class is typically neither associated with instances of the enclosing class nor instantiated along with its enclosing class. Depending on the language, it may or may not be possible to refer to the class from outside the enclosing class. A related concept is ''inner types'', also known as ''inner data type'' or ''nested type'', which is a generalization of the concept of inner classes. [[C++]] is an example of a language that supports both inner classes and inner types (via ''[[typedef]]'' declarations).<ref>{{cite web |url=http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr061.htm |title=Nested classes (C++ only) |work=XL C/C++ V8.0 for AIX |publisher=IBM |access-date=2012-05-07}}</ref><ref> {{cite web |url=http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr063.htm |title=Local type names (C++ only) |work=XL C/C++ V8.0 for AIX |publisher=IBM |access-date=2012-05-07}}</ref> A ''local class'' is a class defined within a procedure or function. Such structure limits references to the class name to within the scope where the class is declared. Depending on the semantic rules of the language, there may be additional restrictions on local classes compared to non-local ones. One common restriction is to disallow local class methods to access local variables of the enclosing function. For example, in C++, a local class may refer to [[static variable]]s declared within its enclosing function, but may not access the function's [[automatic variable]]s.<ref>{{cite web |url=http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr062.htm |title=Local classes (C++ only) |work=XL C/C++ V8.0 for AIX |publisher=IBM |access-date=2012-05-07}}</ref> ===Metaclass=== {{Main|Metaclass}} A metaclass is a class where instances are classes.{{sfn|Booch|1994|p=133-134}} A metaclass describes a common structure of a collection of classes and can implement a [[design pattern (computer science)|design pattern]] or describe particular kinds of classes. Metaclasses are often used to describe [[software framework|framework]]s.<ref>{{Cite web|url=http://pharo.gforge.inria.fr/PBE1/PBE1ch14.html|title=13 Classes and metaclasses|website=pharo.gforge.inria.fr|access-date=2016-10-31|archive-date=2021-02-24|archive-url=https://web.archive.org/web/20210224193450/http://pharo.gforge.inria.fr/PBE1/PBE1ch14.html|url-status=dead}}</ref> In some languages, such as [[Python (programming language)|Python]], [[Ruby (programming language)|Ruby]] or [[Smalltalk]], a class is also an object; thus each class is an instance of a unique metaclass that is built into the language.<ref name="pythondata model"/><ref>{{cite web |url=https://docs.ruby-lang.org/en/master/Class.html |title=class Class}}</ref> {{sfn|Booch|1994|p=134}} The [[Common Lisp Object System]] (CLOS) provides [[Metaobject|metaobject protocols]] (MOPs) to implement those classes and metaclasses.<ref>{{cite web |url=http://www.alu.org/mop/concepts.html#introduction |title=MOP: Concepts |work=The Common Lisp Object System MetaObject Protocol |publisher=Association of Lisp Users |access-date=2012-05-08 |archive-url=https://web.archive.org/web/20101115095930/http://www.alu.org/mop/concepts.html#introduction |archive-date=2010-11-15 |url-status=dead}}</ref> ===Sealed=== <span class="anchor" id="Non-subclassable"></span><span class="anchor" id="Sealed"></span> A sealed class cannot be subclassed. It is basically the opposite of an ''abstract'' class, which must be derived to be used. A sealed class is implicitly ''concrete''. A class is declared as sealed via the keyword {{code|sealed|lang=csharp}} in C# or {{code|final|lang=java}} in Java or PHP.<ref>{{cite web |url=http://msdn.microsoft.com/en-us/library/ms173149.aspx |title=sealed (C# Reference) |work=C# Reference |publisher=Microsoft |access-date=2012-05-08}}</ref><ref> {{cite web |url=http://docs.oracle.com/javase/tutorial/java/IandI/final.html |title=Writing Final Classes and Methods |work=The Java Tutorials |publisher=Oracle |access-date=2012-05-08}}</ref><ref> {{cite web |url=http://php.net/manual/en/language.oop5.final.php |title=PHP: Final Keyword |work=PHP Manual |publisher=The PHP Group |access-date=2014-08-21}}</ref> For example, Java's {{Java|String}} class is marked as ''final''.<ref>{{cite web |url=http://docs.oracle.com/javase/7/docs/api/java/lang/String.html |title=String (Java Platform SE 7) |work=Java Platform, Standard Edition 7: API Specification |publisher=Oracle |access-date=2012-05-08}}</ref> Sealed classes may allow a compiler to perform optimizations that are not available for classes that can be subclassed.<ref>{{cite web |last1=Brand |first1=Sy |title=The Performance Benefits of Final Classes |url=https://devblogs.microsoft.com/cppblog/the-performance-benefits-of-final-classes/ |website=Microsoft C++ team blog |date=2 March 2020 |publisher=Microsoft |access-date=4 April 2020}}</ref> <!-- The following goes without saying, i.e., it says nothing but to hint that "abstract" and "concrete" are an "either but not both" concept. 'abstract' and 'concrete' are defined already above.--> <!-- While it is impossible in any object-oriented language to have a class that is both abstract and concrete, it may be possible to have an abstract partial class --> <!-- The following seemingly belongs in the 'method' article --> <!-- It is also possible not to declare the whole class as such, but only the [[Override (object-oriented programming)|override]] as sealed. This classes are used because of efficiency concerns (can be called like static classes) and security (avoids inadvertent modification of the class semantics).<ref>{{cite web |access-date=2011-08-03 |date=2002-03-25 |first=Hanspeter |last=Mössenböck |page=17 |publisher=Institut für Systemsoftware, Johannes Kepler Universität Linz, Fachbereich Informatik |title=Advanced C#: Overriding of Methods |url=http://ssw.jku.at/Teaching/Lectures/CSharp/Tutorial/Part2.pdf}} </ref> --> ===Open<span class="anchor" id="Open class"></span>=== An open class can be changed. Typically, an [[executable program]] cannot be changed by customers. Developers can often change some classes, but typically cannot change standard or built-in ones. In [[Ruby (programming language)#Open classes|Ruby]], all classes are open. In [[Python (programming language)|Python]], classes can be created at runtime, and all can be modified afterward.<ref>{{cite web|title=9. Classes|url=https://docs.python.org/3.3/tutorial/classes.html|website=The Python Tutorial|publisher=Python.org|access-date=3 March 2018|quote=As is true for modules, classes partake of the dynamic nature of Python: they are created at runtime, and can be modified further after creation.}}</ref> [[Objective-C#Categories|Objective-C categories]] permit the programmer to add methods to an existing class without the need to recompile that class or even have access to its source code. ===Mixin=== Some languages have special support for [[mixin]]s, though, in any language with multiple inheritance, a mixin is simply a class that does not represent an is-a-type-of relationship. Mixins are typically used to add the same methods to multiple classes; for example, a class {{Mono|UnicodeConversionMixin}} might provide a method called {{Mono|unicode_to_ascii}} when included in classes {{Mono|FileReader}} and {{Mono|WebPageScraper}} that do not share a common parent. ===Partial=== In languages supporting the feature, a ''partial class'' is a class whose definition may be split into multiple pieces, within a single [[source code|source-code]] file or across multiple files.<ref name="mspartial">{{Citation|url=https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/partial-classes-and-methods|title=Partial Classes and Methods|work=C# Programming Guide|date=2015-09-19|author1=mairaw|author2=BillWagner|author3=tompratt-AQ|publisher=Microsoft|access-date=2018-08-08}}</ref> The pieces are merged at compile time, making compiler output the same as for a non-partial class. The primary motivation for the introduction of partial classes is to facilitate the implementation of [[Automatic programming|code generators]], such as [[visual designer]]s.<ref name="mspartial"/> It is otherwise a challenge or compromise to develop code generators that can manage the generated code when it is interleaved within developer-written code. Using partial classes, a code generator can process a separate file or coarse-grained partial class within a file, and is thus alleviated from intricately interjecting generated code via extensive parsing, increasing compiler efficiency and eliminating the potential risk of corrupting developer code. In a simple implementation of partial classes, the compiler can perform a phase of [[precompilation]] where it "unifies" all the parts of a partial class. Then, compilation can proceed as usual. <ref>{{cite web | url=https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/partial-classes-and-methods | title=Partial Classes and Members - C# }}</ref> Other benefits and effects of the partial class feature include: * Enables separation of a class's interface and implementation code in a unique way. * Eases navigation through large classes within an [[source code editor|editor]]. * Enables [[separation of concerns]], in a way similar to [[aspect-oriented programming]] but without using any extra tools. * Enables multiple developers to work on a single class concurrently without the need to merge individual code into one file at a later time.<!-- (This enabling may be considered by some or most to be a detriment rather than a benefit for SoC can apply to programmers also).--> Partial classes have existed in [[Smalltalk]] under the name of ''Class Extensions'' for considerable time. With the arrival of the [[.NET Framework|.NET framework 2]], [[Microsoft]] introduced partial classes, supported in both [[C Sharp (programming language)|C#]] 2.0 and [[Visual Basic .NET|Visual Basic 2005]]. [[WinRT]] also supports partial classes. <ref>{{Cite web |last=BillWagner |date=2024-11-14 |title=Partial Classes and Methods - C# |url=https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/partial-classes-and-methods |access-date=2025-02-06 |website=learn.microsoft.com |language=en-us}}</ref> ===Uninstantiable=== ''Uninstantiable classes'' allow programmers to group together per-class fields and methods that are accessible at runtime without an instance of the class. Indeed, instantiation is prohibited for this kind of class. For example, in C#, a class marked "static" can not be instantiated, can only have static members (fields, methods, other), may not have ''instance constructors'', and is ''sealed''. <ref>{{cite web |url=http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.100).aspx |title=Static Classes and Static Class Members (C# Programming Guide) |work=C# Programming Guide |publisher=Microsoft |access-date=2012-05-08}} </ref> ===Unnamed=== An ''unnamed class'' or ''anonymous class'' is not bound to a name or identifier upon definition.<ref>{{Cite web|title=Anonymous Classes (The Java Tutorials > Learning the Java Language > Classes and Objects)|url=https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html|access-date=2021-05-13|website=docs.oracle.com}}</ref><ref>{{Cite web|title=PHP: Anonymous classes - Manual|url=https://www.php.net/manual/en/language.oop5.anonymous.php|access-date=2021-08-11|website=www.php.net}}</ref> This is analogous to named versus [[anonymous function|unnamed functions]]. == Benefits == The benefits of organizing software into object classes fall into three categories:<ref>{{cite web|title=What is an Object?|url=http://docs.oracle.com/javase/tutorial/java/concepts/object.html|work=oracle.com|publisher=Oracle Corporation|access-date=13 December 2013}}</ref> * Rapid development * Ease of maintenance * Reuse of code and designs Object classes facilitate rapid development because they lessen the semantic gap between the code and the users. System analysts can talk to both developers and users using essentially the same vocabulary, talking about accounts, customers, bills, etc. Object classes often facilitate rapid development because most object-oriented environments come with powerful debugging and testing tools. Instances of classes can be inspected at run time to verify that the system is performing as expected. Also, rather than get dumps of core memory, most object-oriented environments have interpreted debugging capabilities so that the developer can analyze exactly where in the program the error occurred and can see which methods were called to which arguments and with what arguments.<ref>{{cite book|last=Booch|first=Grady|title=Object-Oriented Analysis and Design with Applications|publisher=Addison-Wesley Professional|isbn=978-0-201-89551-3|pages=1–28|url=http://my.safaribooksonline.com/book/software-engineering-and-development/object/9780201895513|author2=Robert A. Maksimchuk |author3=Michael W. Engle |author4=Bobbi J. Young Ph.D. |author5=Jim Conallen |author6= Kelli A. Houston |access-date=20 December 2013|date=April 30, 2007|quote=There are fundamental limiting factors of human cognition; we can address these constraints through the use of decomposition, abstraction, and hierarchy.}}</ref> Object classes facilitate ease of maintenance via encapsulation. When developers need to change the behavior of an object they can localize the change to just that object and its component parts. This reduces the potential for unwanted side effects from maintenance enhancements. Software reuse is also a major benefit of using Object classes. Classes facilitate re-use via inheritance and interfaces. When a new behavior is required it can often be achieved by creating a new class and having that class inherit the default behaviors and data of its superclass and then tailoring some aspect of the behavior or data accordingly. Re-use via interfaces (also known as methods) occurs when another object wants to invoke (rather than create a new kind of) some object class. This method for re-use removes many of the common errors that can make their way into software when one program re-uses code from another.<ref>{{cite book|last=Jacobsen|first=Ivar|title=Object Oriented Software Engineering|year=1992|publisher=Addison-Wesley ACM Press|isbn=0-201-54435-0|author2=Magnus Christerson|author3=Patrik Jonsson|author4=Gunnar Overgaard|url=https://archive.org/details/objectorientedso00jaco}}</ref> == Runtime representation == {{Citations needed|Runtime representation|date=May 2024}} As a data type, a class is usually considered as a compile time construct.<ref>{{cite web |title=C++ International standard |url=http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4713.pdf |archive-url=https://web.archive.org/web/20171209100334/http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2017/n4713.pdf |archive-date=2017-12-09 |url-status=live |website=Working Draft, Standard for Programming Language C++ |publisher=ISO/IEC JTC1/SC22 WG21 |access-date=5 January 2020}}</ref> A language or library may also support [[Prototype-based programming|prototype]] or [[Factory method pattern|factory]] [[metaobject]]s that represent runtime information about classes, or even represent metadata that provides access to [[reflective programming]] (reflection) facilities and ability to manipulate data structure formats at runtime. Many languages distinguish this kind of [[run-time type information]] about classes from a class on the basis that the information is not needed at runtime. Some dynamic languages do not make strict distinctions between runtime and compile time constructs, and therefore may not distinguish between metaobjects and classes. For example, if Human is a [[metaobject]] representing the class Person, then instances of class Person can be created by using the facilities of the Human [[metaobject]]. ==Prototype-based programming== In contrast to creating an object from a class, some programming contexts support object creation by copying (cloning) a [[prototype-based programming|prototype]] object.<ref>{{Cite web |last=Amir |first=Masroor |title=OOP - Object Oriented Programming - Concepts {{!}} Languages {{!}} Benefits [2023] |url=https://www.thegeeksbot.com/2023/03/object-oriented-programming.html |access-date=2023-04-04 |website=The Geeks Bot {{!}} A Computer Science Site for geeks |date=25 March 2023 |language=en}}</ref> == See also == {{Portal|Computer programming}} * {{Annotated link|Class diagram}} * {{Annotated link|Class variable}} * {{Annotated link|Instance variable}} * {{Annotated link|List of object-oriented programming languages}} * {{Annotated link|Trait (computer programming)}} == Notes == {{Notelist}} {{Reflist|30em}} == References == {{Refbegin}} * {{cite book |last=Booch |first=Grady |year=1994 |title=Objects and Design with Applications, Second Edition |publisher=Benjamin/Cummings}} * {{cite book |last1=Gamma |last2=Helm |last3=Johnson |last4=Vlissides |year=1995 |title=Design Patterns: Elements of Reusable Object-Oriented Software |url=https://archive.org/details/designpatternsel00gamm |url-access=registration |publisher=Addison Wesley |isbn=9780201633610}} * {{cite book |isbn=978-0-262-02523-2 |title=Foundations of Object-Oriented Languages: Types and Semantics |last=Bruce |first=Kim B. |year=2002 |publisher=MIT Press |location=Cambridge, Massachusetts |url=http://mitpress.mit.edu/books/foundations-object-oriented-languages}} {{Refend}} == Further reading == * [http://lucacardelli.name/TheoryOfObjects.html Abadi; Cardelli: A Theory of Objects] * [http://www.open-std.org/jtc1/sc22/wg21/ ISO/IEC 14882:2003 Programming Language C++, International standard] * [http://www.laputan.org/reflection/warfare.html Class Warfare: Classes vs. Prototypes], by Brian Foote * Meyer, B.: "Object-oriented software construction", 2nd edition, Prentice Hall, 1997, {{ISBN|0-13-629155-4}} * Rumbaugh et al.: "Object-oriented modeling and design", Prentice Hall, 1991, {{ISBN|0-13-630054-5}} {{Types of programming languages}} {{Data types}} {{DEFAULTSORT:Class (Computer Programming)}} [[Category:Class (computer programming)| ]] [[Category:Programming constructs]] [[Category:Programming language topics]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Annotated link
(
edit
)
Template:Citation
(
edit
)
Template:Citations needed
(
edit
)
Template:Cite book
(
edit
)
Template:Cite web
(
edit
)
Template:Code
(
edit
)
Template:Data types
(
edit
)
Template:Em
(
edit
)
Template:Endash
(
edit
)
Template:Further
(
edit
)
Template:ISBN
(
edit
)
Template:Java
(
edit
)
Template:Main
(
edit
)
Template:Mdashb
(
edit
)
Template:Mono
(
edit
)
Template:Notelist
(
edit
)
Template:Portal
(
edit
)
Template:Redirect
(
edit
)
Template:Refbegin
(
edit
)
Template:Refend
(
edit
)
Template:Reflist
(
edit
)
Template:See also
(
edit
)
Template:Sfn
(
edit
)
Template:Short description
(
edit
)
Template:Types of programming languages
(
edit
)
Template:Vanchor
(
edit
)