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)
(section)
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!
==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]]). -->
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)