Anda di halaman 1dari 9

In object-oriented programming, a class is a construct that is used to define a distinct type.

The class is instantiated into instances of itself referred to as class instances, class objects, instance objects or simply objects. A class def ines constituent members that enable its instances to have state and behavior.[1 ] Data field members (member variables or instance variables) enable a class ins tance to maintain state. Other kinds of members, especially methods, enable the behavior of class instances. Classes therefore define the type of their instance s.[2] A class usually represents a noun, such as a person, place or thing, or somethin g nominalized. For example, a "Banana" class would represent the properties and functionality of bananas in general. A single, particular banana would be an ins tance of the "Banana" class, an object of the type "Banana". Contents 1 Design and implementation 1.1 Structure 1.2 Behavior 1.3 The concept of class interface 1.3.1 Example 1.4 Member accessibility 2 Inter-class relationships 2.1 Compositional 2.2 Hierarchical 2.2.1 Definitions of subclass 2.3 Orthogonality of the class concept and inheritance 2.4 Within object-oriented analysis 3 Taxonomy of classes 3.1 Abstract and Concrete 3.2 Local and inner 3.3 Metaclasses 3.4 Non-subclassable 3.5 Partial 3.5.1 Example in VB.NET 3.5.2 Example in Objective-C 3.6 Uninstantiable 3.7 Unnamed 4 Benefits 5 Run-time representation 6 See also 7 Notes 8 References 9 Further reading 10 External links Design and implementation Classes are composed from structural and behavioral constituents.[3] Programming languages that include classes as a programming construct offer support for var ious class-related features, and the syntax required to use these features varie s greatly from one programming language to another. Structure UML notation for classes A class contains data field descriptions (or properties, fields, data members, o r attributes). These are usually field types and names that will be associated w ith 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 d efined by the class determines the layout of the memory used by its instances. O ther implementations are possible: for example, objects in Python use associativ

e key-value containers.[4] Some programming languages support specification of invariants as part of the de finition of the class, and enforce them through the type system. Encapsulation o f state is necessary for being able to enforce the invariants of the class. Behavior Main article: Method (computer programming) The behavior of class or its instances is defined using methods. Methods are sub routines 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.[5] Many ki nds of methods exist, but support for them varies across languages. Some types o f methods are created and called by programmer code, while other special methods s uch as constructors, destructors, and conversion operators are created and called by compiler-generated code. A language may also allow the programmer to define a nd call these special methods.[6][7] The concept of class interface Main article: Interface (computing) Every class implements (or realizes) an interface by providing structure and beh avior. Structure consists of data and state, and behavior consists of code that specifies how methods are implemented.[8] There is a distinction between the def inition of an interface and the implementation of that interface; however, this line is blurred in many programming languages because class declarations both de fine and implement an interface. Some languages, however, provide features that separate interface and implementation. For example, an abstract class can define an interface without providing implementation. Languages that support class inheritance also allow classes to inherit interface s from the classes that they are derived from.[example needed] In languages that support 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 impl icit 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 th e interface. Object-oriented programming methodology dictates that the operations of any inte rface of a class are to be independent of each other. It results in a layered de sign 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 in terface 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 th e client has access to the object.[citation needed] Example The buttons on the front of your television set are the interface between you an d 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 particu lar television is the instance, each method is represented by a button, and all the buttons together comprise 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 associat ed implementation of the methods. A television set also has a myriad of attributes, such as size and whether it su pports 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 clearly associated with the class, yet is outside the domain of each individual instance of the class. Another example wou ld be a static method that finds a particular instance out of the set of all tel evision objects. Member accessibility Further information: Information hiding Many languages support the concept of information hiding and encapsulation, typi cally with access specifiers for class members. Access specifiers control access to class members. Some access specifiers may also control how classes inherit s uch constraints. Their primary purpose is to separate the interface of a class f rom its implementation. The following is a common set of access specifiers:[9] private (or class-private) restricts the access to the class itself. Only me thods that are part of the same class can access private members. protected (or class-protected) allows the class itself and all its subclasse s 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, the ir semantics may differ. Object-oriented design uses the access specifiers in conjunction with careful de sign of public method implementations to enforce class invariants constraints on t he 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 priv ate, while public accessor methods can be used to inspect or alter such private data. Access specifiers do not necessarily control visibility, in that even private me mbers may be visible to client external code. In some languages, an inaccessible but visible member may be referred to at run-time (for example, by a pointer re turned from a member function), but an attempt to use it by referring to the nam e of the member from client code will be prevented by the type checker.[10] The various object-oriented programming languages enforce member accessibility a nd visibility to various degrees, and depending on the language's type system an d compilation policies, enforced at either compile-time or run-time. For example , the Java language does not allow client code that accesses the private data of a class to compile. [11] In the C++ language, private methods are visible, but not accessible in the interface; however, they may be made invisible by explicit ly declaring fully abstract classes that represent the interfaces of the class.[ 12] Some languages feature other accessibility schemes: Instance vs. class accessibility: Ruby supports instance-private and instanc e-protected access specifiers in lieu of class-private and class-protected, resp ectively. They differ in that they restrict access based on the instance itself, rather than the instance's class.[13] Friend: C++ supports a mechanism where a function explicitly declared as a f riend function of the class may access the members designated as private or prot ected.[14] Path-based: Java supports restricting access to a member within a Java packa ge, which is roughly the path of a file.[9]

Inter-class relationships In addition to the design of standalone classes, programming languages may suppo rt more advanced class design based upon relationships between classes. The inte r-class relationship design capabilities commonly provided are compositional and hierarchical. Compositional Classes can be composed of other classes, thereby establishing a compositional r elationship between the enclosing class and its embedded classes. Compositional relationship between classes is also commonly known as a has-a relationship.[15] For example, a class "Car" could be composed of and contain a class "Engine". T herefore, a Car has an Engine. One aspect of composition is containment, which i s the enclosure of component instances by the instance that has them. If an encl osing object contains component instances by value, the components and their enc losing object have a similar lifetime. If the components are contained by refere nce, they may not have a similar lifetime.[16] For example, in Objective-C 2.0: @interface Car : NSObject @property NSString *name; @property Engine *engine @property NSArray *tyres; @end This Car class has an instance of NSString (string object), Engine, and NSArray (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, paren t classes or superclasses) 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.[17] For example, a class 'Button' could be derived fro m 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/or behavioral member s (methods) in addition to those that they inherit and are therefore specializat ions of their superclasses. Also, derived classes can 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.[18] If multi ple inheritance is allowed, the hierarchy is a directed acyclic graph (or DAG fo r short), otherwise it is a tree. The hierarchy has classes as nodes and inherit ance relationships as links. Classes in the same level are more likely to be ass ociated than classes in different levels. The levels of this hierarchy are calle d layers or levels of abstraction. Example (Simplified Objective-C 2.0 code, from iPhone SDK): @interface @interface @interface @interface UIResponder : NSObject //... UIView : UIResponder //... UIScrollView : UIView //... UITableView : UIScrollView //...

In this example, a UITableView is a UIScrollView is a UIView is a UIResponder is an NSObject. Definitions of subclass

Main articles: Inheritance (object-oriented programming), Superclass (computer s cience), and Subclass (computer science) Question book-new.svg This section does not cite any references or sources. Please help improv e this section by adding citations to reliable sources. Unsourced material may b e challenged and removed. (May 2012) Conceptually, a superclass should be considered as a common part of its subclass es. This factoring of commonality is one mechanism for providing reuse. Thus, ex tending a superclass by modifying the existing class is also likely to narrow it s applicability in various situations. In object-oriented design, careful balanc e between applicability and functionality of superclasses should be considered. Subclassing is different from subtyping in that subtyping deals with common beha vior whereas subclassing is concerned with common structure. There are two different points of view as to whether subclasses of the same clas s are required to be disjoint. Sometimes, subclasses of a particular class are c onsidered to be completely disjoint. That is, every instance of a class has exac tly one most-derived class, which is a subclass of every class that the instance has. This view does not allow dynamic change of object's class, as objects are assumed to be created with a fixed most-derived class. The basis for not allowin g changes to object's class is that the class is a compile-time type, which does not usually change at runtime, and polymorphism is utilized for any dynamic cha nge to the object's behavior, so this ability is not necessary. Design that does not need to perform changes to object's type will be more robust and easy-to-us e from the point of view of the users of the class. From another point of view, subclasses are not required to be disjoint. Then the re is no concept of a most-derived class, and all types in the inheritance hiera rchy that are types of the instance are considered to be equally types of the in stance. This view is based on a dynamic classification of objects, such that an object may change its class at runtime. Then object's class is considered to be its current structure, but changes to it are allowed. The basis for allowing cha nges to object's class is a perceived inconvenience caused by replacing an insta nce with another instance of a different type, since this would require change o f all references to the original instance to be changed to refer to the new inst ance. When changing the object's class, references to the existing instances do not need to be replaced with references to new instances when the class of the o bject changes. However, this ability is not readily available in all programming languages. This analysis depends on the proposition that dynamic changes to obj ect structure are common. This may or may not be the case in practice. Orthogonality of the class concept and inheritance Although class-based languages are commonly assumed to support inheritance, inhe ritance is not an intrinsic aspect of the concept of classes. Some languages, of ten referred to as "object-based languages", support classes yet do not support inheritance. Examples of object-based languages include earlier versions of Visu al Basic. Within object-oriented analysis Main article: Association (object-oriented programming) In object-oriented analysis and in UML, an association between two classes repre sents a collaboration between the classes or their corresponding instances. Asso ciations have direction; for example, a bi-directional association between two c lasses indicates that both of the classes are aware of their relationship.[19] A ssociations may be labeled according to their name or purpose.[20] 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 instanc es of the class "Person" participate in a "subscribes-to" association with the c

lass "Magazine". Also, a "Magazine" has the "subscribed magazine" role in the sa me association. Association role multiplicity describes how many instances corre spond to each instance of the other class of the association. Common multiplicit ies are "0..1", "1..1", "1..*" and "0..*", where the "*" specifies any number of instances.[19] Taxonomy of classes There are many categories of classes; however, these categories do not necessari ly divide classes into distinct partitions. Abstract and Concrete Main article: Abstract type In a language that supports inheritance, an abstract class, or abstract base cla ss (ABC), is a class that cannot be instantiated because it is either labeled as abstract or it simply specifies abstract methods (or virtual methods). Abstract classes specify virtual methods via signatures that are to be implemented by di rect or indirect descendents of the abstract class. Before a class derived from an abstract class can be instantiated, all abstract methods of its parent classe s must be implemented by some class in the derivation chain.[21] Most object oriented programming languages allow the programmer to specify which classes are considered abstract and will not allow these to be instantiated. Fo r example, in Java and PHP, the keyword abstract is used.[22][23] In C++, an abs tract class is a class having at least one abstract method given by the appropri ate syntax in that language (a pure virtual function in C++ parlance).[21] 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. [12] 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. [18] [24] [25] A concrete class is a class that can be instantiated, as opposed to abstract cla sses, which cannot. 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. Dependi ng on 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 type s (via typedef declarations). [26] [27] Another type is a local class, which is a class defined within a procedure or fu nction. This limits references to the class name to within the scope where the c lass is declared. Depending on the semantic rules of the language, there may be additional restrictions on local classes compared non-local ones. One common res triction is to disallow local class methods to access local variables of the enc losing 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 auto matic variables. [28] Metaclasses Main article: Metaclass

Metaclasses are classes whose instances are classes.[29] 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.[citation needed] 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 which is built into the la nguage. [4] [30] [31] For example, in Objective-C, each object and class is an i nstance of NSObject. [32] The Common Lisp Object System (CLOS) provides metaobje ct protocols (MOPs) to implement those classes and metaclasses. [33] Non-subclassable Non-subclassable classes allow programmers to design classes and hierarchies of classes which at some level in the hierarchy, further derivation is prohibited. (A stand-alone class may be also designated as non-subclassable, preventing the formation of any hierarchy). Contrast this to abstract classes, which imply, enc ourage, and require derivation in order to be used at all. A non-subclassable cl ass is implicitly concrete. A non-subclassable class is created by declaring the class as sealed in C# or as final in Java. [34] [35] For example, Java's String class is designated as fina l. [36] Non-subclassable classes may allow a compiler (in compiled languages) to perform optimizations that are not available for subclassable classes.[citation needed] Partial Question book-new.svg This section does not cite any references or sources. Please help improv e this section by adding citations to reliable sources. Unsourced material may b e challenged and removed. (April 2012) 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 m ultiple files. The pieces are merged at compile-time, making compiler output the same as for a non-partial class. The primary motivation for introduction of partial classes is to facilitate the implementation of code generators, such as visual designers. It is otherwise a c hallenge 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 w ithin a file, and is thus alleviated from intricately interjecting generated cod e via extensive parsing, increasing compiler efficiency and eliminating the pote ntial risk of corrupting developer code. In a simple implementation of partial c lasses, the compiler can perform a phase of precompilation where it "unifies" al l 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 uniqu e way. Eases navigation through large classes within an editor. Enables separation of concerns, in a way similar to aspect-oriented programm ing but without using any extra tools. Enables multiple developers to work on a single class concurrently without t he need to merge individual code into one file at a later time.

Partial classes have existed in Smalltalk under the name of Class Extensions for considerable time. With the arrival of the .NET framework 2, Microsoft introduc ed partial classes, supported in both C# 2.0 and Visual Basic 2005. WinRT also s upports partial classes. Example in VB.NET This simple example, written in Visual Basic .NET, shows how parts of the same c lass are defined in two different files. file1.vb Partial Class MyClass Private _name As String End Class file2.vb Partial Class MyClass Public Readonly Property Name() As String Get Return _name End Get End Property End Class When compiled, the result is the same as if the two files were written as one, l ike this: Class MyClass Private _name As String Public Readonly Property Name() As String Get Return _name End Get End Property End Class Example in Objective-C In Objective-C, partial classes, aka categories may even spread over multiple li braries and executables, like this example: In Foundation, header file NSData.h: @interface NSData : NSObject - (id)initWithContentsOfURL:(NSURL *)URL; //... @end In user-supplied library, a separate binary from Foundation framework, header fi le NSData+base64.h: #import <Foundation/Foundation.h> @interface NSData (base64) - (NSString *)base64String; - (id)initWithBase64String:(NSString *)base64String;

@end And in an app, yet another separate binary file, source code file main.m: #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]]; NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:so urceURLString]]; NSLog(@"%@", [data base64String]); return EXIT_SUCCESS; } The dispatcher will find both methods called over the NSData instance and invoke both of them correctly. 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 ha ve static members (fields, methods, other), may not have instance constructors, and is sealed. [37] Unnamed An unnamed class or anonymous class is a class which is not bound to a name or i dentifier upon definition. This is analogous to named versus unnamed functions.

Anda mungkin juga menyukai