Class (computer programming)

From Wikipedia, the free encyclopedia
Jump to navigation Jump to search

In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods).[1][2] In many languages, the class name is used as the name for the class (the template itself), the name for the default constructor of the class (a subroutine that creates objects), and as the type of objects generated by instantiating the class; these distinct concepts are easily conflated.[2]


In some languages, classes are only a compile-time feature (new classes cannot be declared at run-time), while in other languages classes are first-class citizens, and are generally themselves objects (typically of type Class or similar). In these languages, a class that creates classes is called a metaclass.

Class vs. type[edit]

In casual use, people often refer to the "class" of an object, but narrowly speaking objects have type: the interface, namely the types of member variables, the signatures of member functions (methods), and properties these satisfy. At the same time, a class has an implementation (specifically the implementation of the methods), and can create objects of a given type, with a given implementation.[3] In the terms of type theory, a class is an implementation‍—‌a concrete data structure and collection of subroutines‍—‌while a type is an interface. Different (concrete) classes can produce objects of the same (abstract) type (depending on type system); for example, the type Stack might be implemented with two classes – SmallStack (fast for small stacks, but scales poorly) and ScalableStack (scales well but high overhead for small stacks). Similarly, a given class may have several different constructors.

Class types generally represent nouns, such as a person, place or thing, or something nominalized, and a class represents an implementation of these. For example, a Banana type might represent the properties and functionality of bananas in general, while the ABCBanana and XYZBanana classes would represent ways of producing bananas (say, banana suppliers or data structures and functions to represent and draw bananas in a video game). The ABCBanana class could then produce particular bananas: instances of the ABCBanana class would be objects of type Banana. Often only a single implementation of a type is given, in which case the class name is often identical with the type name.

Design and implementation[edit]

Classes are composed from structural and behavioral constituents.[4] Programming languages that include classes as a programming construct offer support, for various class-related features, and the syntax required to use these features varies greatly from one programming language to another.


UML notation for classes





The concept of class interface[edit]



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".




The buttons on the front of your television set are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to toggle the television on and off. In this example, your particular television is the instance, each method is represented by a button, and all the buttons together compose the interface (other television sets that are the same model as yours would have the same interface). In its most common form, an interface is a specification of a group of related methods without any associated implementation of the methods.

A television set also has a myriad of attributes, such as size and whether it supports colour, which together comprise its structure. A class represents the full description of a television, including its attributes (structure) and buttons (interface).

Getting the total number of televisions manufactured could be a static method of the television class. This method is clearly associated with the class, yet is outside the domain of each individual instance of the class. A static method that finds a particular instance out of the set of all television objects is another example.

Member accessibility[edit]

The following is a common set of access specifiers:[11]

  • 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.





Some languages feature other accessibility schemes:


Inter-class relationships[edit]




@interface Car : NSObject

@property NSString *name;
@property Engine *engine
@property NSArray *tires;







@interface UIResponder : NSObject //...
@interface UIView : UIResponder //...
@interface UIScrollView : UIView //...
@interface UITableView : UIScrollView //...


Definitions of subclass[edit]

Conceptually, a superclass is a superset of its subclasses. For example, a common class hierarchy would involve GraphicObject as 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 component parts of the car as subclass relations. For example, a car is composed of an engine and body, but it would not be appropriate to model engine or body as a subclass of car.

In object-oriented modeling 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 beside the basic data definitions for the objects, such as error checking on get and set methods.[21]





Orthogonality of the class concept and inheritance[edit]


Within object-oriented analysis[edit]

In object-oriented analysis and in 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.[24] Associations may be labeled according to their name or purpose.[25]


Taxonomy of classes[edit]

There are many categories of classes, some of which overlap.

Abstract and concrete[edit]


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.[27][28] 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).[26]

A class consisting of only virtual methods is called a Pure Abstract Base Class (or Pure ABC) in C++ and is also known as an interface by users of the language.[14] 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.[20][29][30]


Local and inner[edit]





Metaclasses are classes whose instances are classes.[34] 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.[35]

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. [5] [36] [37] The Common Lisp Object System (CLOS) provides metaobject protocols (MOPs) to implement those classes and metaclasses. [38]



A non-subclassable class is created by declaring the class as sealed in C# or as final in Java or PHP.[39][40][41] For example, Java's String class is designated as final.[42]


Open Class[edit]

An open class is one that 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 afterwards.[44] 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.


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 UnicodeConversionMixin might provide a method called unicode_to_ascii when included in classes FileReader and WebPageScraper that do not share a common parent.


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.[45] The pieces are merged at compile-time, making compiler output the same as for a non-partial class.


Other benefits and effects of the partial class feature include:

  • Eases navigation through large classes within an editor.


Example in VB.NET[edit]


Partial Class MyClass
    Private _name As String
End Class
Partial Class MyClass
    Public Readonly Property Name() As String
             Return _name
         End Get
    End Property
End Class


Class MyClass
    Private _name As String
    Public Readonly Property Name() As String
             Return _name
         End Get
    End Property
End Class

Example in Objective-C[edit]

In Objective-C, partial classes, also known as categories, may even spread over multiple libraries and executables, like the following example. But a key difference is that Objective-C's categories can overwrite definitions in another interface declaration, and that categories aren't equal to original class definition (the first requires the last).[46] Instead, .NET partial class can't have conflicting definitions, and all partial definitions are equal to the others.[45]

In Foundation, header file NSData.h:

@interface NSData : NSObject

- (id)initWithContentsOfURL:(NSURL *)URL;



#import <Foundation/Foundation.h>

@interface NSData (base64)

- (NSString *)base64String;
- (id)initWithBase64String:(NSString *)base64String;



#import <Foundation/Foundation.h>
#import "NSData+base64.h"

int main(int argc, char *argv[])
    if (argc < 2)
        return EXIT_FAILURE;
    NSString *sourceURLString = [NSString stringWithCString:argv[1]];
    return EXIT_SUCCESS;






An unnamed class or anonymous class is a class that is not bound to a name or identifier upon definition. This is analogous to named versus unnamed functions.


The benefits of organizing software into object classes fall into three categories:[48]

  • Rapid development
  • Ease of maintenance
  • Reuse of code and designs


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.


Run-time representation[edit]

As a data type, a class is usually considered as a compile-time construct.[51] A language or library may also support prototype or factory metaobjects that represent run-time information about classes, or even represent metadata that provides access to reflection facilities and ability to manipulate data structure formats at run-time. 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 run-time. Some dynamic languages do not make strict distinctions between run-time and compile-time constructs, and therefore may not distinguish between metaobjects and classes.


See also[edit]


  6. ^ Booch 1994, p. 86-88.
  9. ^ Booch 1994, p. 105.
  10. ^ Jamrich, Parsons, June (2015-06-22). New perspectives computer concepts, 2016. Comprehensive. Boston, MA. ISBN 9781305271616. OCLC 917155105.
  12. ^ "OOP08-CPP. Do not return references to private data". CERT C++ Secure Coding Standard. Carnegie Mellon University. 2010-05-10. Archived from the original on 2015-10-03. Retrieved 2012-05-07.
  13. ^ Ben-Ari, Mordechai (2007-01-24). "2.2 Identifiers" (PDF). Compile and Runtime Errors in Java. Retrieved 2012-05-07.
  17. ^ Booch 1994, p. 180.
  18. ^ Booch 1994, p. 128-129.
  19. ^ Booch 1994, p. 112.
  21. ^ Berfeld, Marya (2 December 2008). "UML-to-Java transformation in IBM Rational Software Architect editions and related software". IBM. Retrieved 20 December 2013.
  25. ^ Booch 1994, p. 179.
  34. ^ Booch 1994, p. 133-134.
  35. ^ "13 Classes and metaclasses". Retrieved 2016-10-31.
  37. ^ Booch 1994, p. 134.
  38. ^ "MOP: Concepts". The Common Lisp Object System MetaObject Protocol. Association of Lisp Users. Archived from the original on 2010-11-15. Retrieved 2012-05-08.
  43. ^ Brand, Sy. "The Performance Benefits of Final Classes". Microsoft C++ team blog. Microsoft. Retrieved 4 April 2020.
  44. ^ "9. Classes". The Python Tutorial. Retrieved 3 March 2018. 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.
  45. ^ a b c mairaw; BillWagner; tompratt-AQ (2015-09-19), "Partial Classes and Methods", C# Programming Guide, Microsoft, retrieved 2018-08-08
  46. ^ Apple (2014-09-17), "Customizing Existing Classes", Programming with Objective-C, Apple, retrieved 2018-08-08
  51. ^ "C++ International standard" (PDF). Working Draft, Standard for Programming Language C++. ISO/IEC JTC1/SC22 WG21. Retrieved 5 January 2020.


Further reading[edit]

External links[edit]