In
object-oriented programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impl ...
, a class defines the shared aspects of
objects created from the class. The capabilities of a class differ between
programming language
A programming language is a system of notation for writing computer programs.
Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s, 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.
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
Inheritance is the practice of receiving private property, titles, debts, entitlements, privileges, rights, and obligations upon the death of an individual. The rules of inheritance differ among societies and have changed over time. Offi ...
, 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 of a class, an object is constructed from a class via ''instantiation''. Memory is allocated and initialized for the object state and a
reference
A reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a ''nam ...
to the object is provided to consuming code. The object is usable until it is destroyed 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
In computer science and computer programming, a data type (or simply type) is a collection or grouping of data values, usually specified by a set of possible values, a set of allowed operations on these values, and/or a representation of these ...
as an interface 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. In the terms of type theory, a class is an implementationa ''concrete''
data structure
In computer science, a data structure is a data organization and storage format that is usually chosen for Efficiency, efficient Data access, access to data. More precisely, a data structure is a collection of data values, the relationships amo ...
and collection of subroutineswhile 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) might be implemented by that is fast for small stacks but scales poorly and that scales well but has high overhead for small stacks.
Structure
A class contains
data
Data ( , ) are a collection of discrete or continuous values that convey information, describing the quantity, quality, fact, statistics, other basic units of meaning, or simply sequences of symbols that may be further interpreted for ...
field descriptions (or ''
properties
Property is the ownership of land, resources, improvements or other tangible objects, or intellectual property.
Property may also refer to:
Philosophy and science
* Property (philosophy), in philosophy and logic, an abstraction characterizing an ...
'', ''
fields'', ''data
members
Member may refer to:
* Military jury, referred to as "Members" in military jargon
* Element (mathematics), an object that belongs to a mathematical set
* In object-oriented programming, a member of a class
** Field (computer science), entries in ...
'', or ''
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 use associative key-value containers.
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
The behavior of a class or its instances is defined using
methods. Methods are
subroutine
In computer programming, a function (also procedure, method, subroutine, routine, or subprogram) is a callable unit of software logic that has a well-defined interface and behavior and can be invoked multiple times.
Callable units provide a ...
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. 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.
Class interface
Every class ''implements'' (or ''realizes'') an interface by providing
structure
A structure is an arrangement and organization of interrelated elements in a material object or system, or the object or system so organized. Material structures include man-made objects such as buildings and machines and natural objects such as ...
and behavior. Structure consists of data and state, and behavior consists of code that specifies how methods are implemented. 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
In object-oriented programming, a class defines the shared aspects of objects created from the class. The capabilities of a class differ between programming languages, but generally the shared aspects consist of state ( variables) and behavior ( ...
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
access specifiers
Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility of classes, methods, and other members. Access modifiers are a specific part of programming language syntax used to facilitate the en ...
, 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.
; 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
The following is a common set of
access specifiers
Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility of classes, methods, and other members. Access modifiers are a specific part of programming language syntax used to facilitate the en ...
:
* ''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 method
In computer science, a mutator method is a method used to control changes to a variable. They are also widely known as setter methods. Often a setter is accompanied by a getter, which returns the value of the private member variable. They are also ...
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.
The various object-oriented programming languages enforce member accessibility and visibility to various degrees, and depending on the language's
type system
In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a ''type'' (for example, integer, floating point, string) to every '' term'' (a word, phrase, or other set of symbols). Usu ...
and compilation policies, enforced at either
compile time
In computer science, compile time (or compile-time) describes the time window during which a language's statements are converted into binary instructions for the processor to execute. The term is used as an adjective to describe concepts relat ...
or
runtime. For example, the
Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
language does not allow client code that accesses the private data of a class to compile. 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.
Some languages feature other accessibility schemes:
* ''Instance vs. class accessibility'':
Ruby
Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
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.
* ''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.
* ''Path-based'': Java supports restricting access to a member within a
Java package
A Java package organizes Java classes into namespaces,
providing a unique namespace for each type it contains.
Classes in the same package can access each other's package-private and protected members.
In general, a package can contain the fo ...
, 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.
[
]
Inheritance
Conceptually, a superclass is a superset
In mathematics, a set ''A'' is a subset of a set ''B'' if all elements of ''A'' are also elements of ''B''; ''B'' is then a superset of ''A''. It is possible for ''A'' and ''B'' to be equal; if they are unequal, then ''A'' is a proper subset ...
of its subclasses. For example, could be a superclass of and , while would be a subclass of . 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
Object-oriented modeling (OOM) is an approach to modeling an application that is used at the beginning of the software life cycle when using an object-oriented approach to software development.
The software life cycle is typically divided up into ...
these kinds of relations are typically modeled as object properties. In this example, the class would have a property called . would be typed to hold a collection of objects, such as instances of , , , 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.
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.
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
The Semantic Web, sometimes known as Web 3.0, is an extension of the World Wide Web through standards set by the World Wide Web Consortium (W3C). The goal of the Semantic Web is to make Internet data machine-readable.
To enable the encoding o ...
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.
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.
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
typedef is a reserved keyword in the programming languages C, C++, and Objective-C. It is used to create an additional name (''alias'') for another data type, but does not create a new type, except in the obscure case of a qualified typedef of ...
'' declarations).
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
In computer programming, a static variable is a variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program. This is in contrast to shorter-lived automatic variables, whose storage is ...
s declared within its enclosing function, but may not access the function's automatic variable
In computer programming, an automatic variable is a local variable which is allocated and deallocated automatically when program flow enters and leaves the variable's scope. The scope is the lexical context, particularly the function or block in ...
s.
Metaclass
A metaclass is a class where instances are classes. A metaclass describes a common structure of a collection of classes and can implement a design pattern
A design pattern is the re-usable form of a solution to a design problem. The idea was introduced by the architect Christopher Alexander and has been adapted for various other disciplines, particularly software engineering. The " Gang of Four" ...
or describe particular kinds of classes. Metaclasses are often used to describe frameworks.
In some languages, such as Python, Ruby
Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
or Smalltalk
Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learni ...
, a class is also an object; thus each class is an instance of a unique metaclass that is built into the language.
The Common Lisp Object System (CLOS) provides metaobject protocols (MOPs) to implement those classes and metaclasses.
Sealed
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 in C# or in Java or PHP.
For example, Java's class is marked as ''final''.
Sealed classes may allow a compiler to perform optimizations that are not available for classes that can be subclassed.
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
Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
, all classes are open. In Python, classes can be created at runtime, and all can be modified afterward. 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 might provide a method called when included in classes and 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. 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. 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.
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
Editing is the process of selecting and preparing written, visual, audible, or cinematic material used by a person or an entity to convey a message or information. The editing process can involve correction, condensation, organization, a ...
.
* Enables separation of concerns
In computer science, separation of concerns (sometimes abbreviated as SoC) is a design principle for separating a computer program into distinct sections. Each section addresses a separate '' concern'', a set of information that affects the code o ...
, 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
Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learni ...
under the name of ''Class Extensions'' for considerable time. With the arrival of the .NET framework 2, Microsoft
Microsoft Corporation is an American multinational corporation and technology company, technology conglomerate headquartered in Redmond, Washington. Founded in 1975, the company became influential in the History of personal computers#The ear ...
introduced partial classes, supported in both C# 2.0 and Visual Basic 2005. WinRT also supports partial classes.
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''.
Unnamed
An ''unnamed class'' or ''anonymous class'' is not bound to a name or identifier upon definition. This is analogous to named versus unnamed functions.
Benefits
The benefits of organizing software into object classes fall into three categories:
* 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.
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.
Runtime representation
As a data type, a class is usually considered as a compile time construct. A language or library may also support prototype
A prototype is an early sample, model, or release of a product built to test a concept or process. It is a term used in a variety of contexts, including semantics, design, electronics, and Software prototyping, software programming. A prototype ...
or factory
A factory, manufacturing plant or production plant is an industrial facility, often a complex consisting of several buildings filled with machinery, where workers manufacture items or operate machines which process each item into another. Th ...
metaobjects that represent runtime information about classes, or even represent metadata that provides access to reflective programming
In computer science, reflective programming or reflection is the ability of a process to examine, introspect, and modify its own structure and behavior.
Historical background
The earliest computers were programmed in their native assembly lang ...
(reflection) facilities and ability to manipulate data structure formats at runtime. Many languages distinguish this kind of run-time type information
In computer programming, run-time type information or run-time type identification (RTTI) is a feature of some programming languages (such as C++, Object Pascal, and Ada) that exposes information about an object's data type at runtime. Run-time ...
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
A prototype is an early sample, model, or release of a product built to test a concept or process. It is a term used in a variety of contexts, including semantics, design, electronics, and Software prototyping, software programming. A prototype ...
object.
See also
*
*
*
*
*
Notes
References
*
*
*
Further reading
Abadi; Cardelli: A Theory of Objects
ISO/IEC 14882:2003 Programming Language C++, International standard
by Brian Foote
* Meyer, B.: "Object-oriented software construction", 2nd edition, Prentice Hall, 1997,
* Rumbaugh et al.: "Object-oriented modeling and design", Prentice Hall, 1991,
{{DEFAULTSORT:Class (Computer Programming)
Programming constructs
Programming language topics