In object-oriented programming, a class is a programming language construct that is used to group related instance variables and methods. A method, called a function in some languages, is a set of instructions that are specific to a class. Depending on the language, classes may support multiple inheritance or may require the use of interfaces to extend other classes. A class may indicate either specifically or abstractly what methods exist when the program is executed. The latter is known as an 'abstract class'.
A class must be defined with a constructor if it is to be used as an object, that is, instantiated. However some classes, especially those containing factory methods, are defined as static classes with no constructor merely to organize data hierarchically (e.g. the Math class may contain the static constant PI
and the static method abs
). A pseudocode example resembling Java syntax is shown below to show the hierarchy:
As shown above, methods exist within classes, but classes may also exist within classes. These are known as inner classes. An important concept to understand when dealing with object-oriented programming is that of scope. Scope refers to the visibility of a data component based upon where it is nested, that is between which set of braces ({}) it occurs. A method within a class may be able to manipulate the global variables of the parent class, but not the instance variables of another method. This is called encapsulation, and is one of the three fundamentals of object-oriented programming.
A class is a cohesive package that consists of a particular kind of compile-time metadata. It describes the rules by which objects behave; these objects are referred to as "instances" of that class. A class specifies the structure of data within each instance as well as the methods (functions) which manipulate the data of the object and perform tasks; such methods are sometimes described as "behavior". A method is a function with a special property that it has access to data stored in an object. A class is the most specific type of an object in relation to a specific layer. A class may also have a representation (metaobject) at runtime, which provides runtime support for manipulating the class-related metadata.
Instances of a class will have certain aspects (aka: features, attributes or properties) in common. A class 'Person' for example would describe the properties common to all instances of the 'Person' class. One of the benefits of programming with classes is that all instances of a particular class will follow the defined behavior of the class they instantiate. Each person is generally alike, but varies in such properties as "height" and "weight". The class would list types of such instance variables; and also define, via methods, the actions which humans can perform: "run", "jump", "sleep", "throw object", etc.