Object-oriented programming: Difference between revisions

Content deleted Content added
Yamin8000 (talk | contribs)
m fixed some spellings
wrangle the sections, they were repeating the same concepts and overlapped
Line 11:
| title = Object-Oriented Simulation of systems with sophisticated control
| publisher = International Journal of General Systems
| year = 2011 | pages = 313–343}}</ref><ref>{{Cite book|last1=Lewis|first1=John|last2=Loftus|first2= William|title=Java Software Solutions Foundations of Programming Design 6th ed|publisher=Pearson Education Inc.|year=2008|isbn=978-0-321-53205-3}}, section 1.6 "Object-Oriented Programming"</ref> OOP languages are diverse, but the most popular ones are [[Class-based programming|class-based]], meaning that objects are [[instance (computer science)|instances]] of [[class (computer science)|classes]], which also determine their [[data type|types]].
 
Many of the most widely used programming languages (such as [[C++]], [[Java (programming language)|Java]],{{sfn|Bloch|2018|loc=Foreword|pp=xi-xii}} [[Python (programming language)|Python]], etc.) are [[multi-paradigm programming language|multi-paradigm]] and they support object-oriented programming to a greater or lesser degree, typically in combination with [[imperative programming]], [[procedural programming]] and [[functional programming]].
Line 90:
[[Modular programming]] support provides the ability to group procedures into files and modules for organizational purposes. Modules are [[namespace]]d so identifiers in one module will not conflict with a procedure or variable sharing the same name in another file or module.
 
===Objects and classes===
Objects sometimes correspond to things found in the real world. For example, a graphics program may have objects such as "circle", "square", and "menu". An online shopping system might have objects such as "shopping cart", "customer", and "product".<ref>{{cite book|last=Booch|first=Grady|title=Software Engineering with Ada|year=1986|publisher=Addison Wesley|isbn=978-0-8053-0608-8|page=220|url=https://en.wikiquote.org/wiki/Grady_Booch|quote=Perhaps the greatest strength of an object-oriented approach to development is that it offers a mechanism that captures a model of the real world.}}</ref> Sometimes objects represent more abstract entities, like an object that represents an open file, or an object that provides the service of translating measurements from U.S. customary to metric. Objects are accessed somewhat like variables with complex internal structures, and in many languages are effectively [[Pointer (computer programming)|pointers]], serving as actual references to a single instance of said object in memory within a heap or stack. Procedures are known as [[Method (computer science)|methods]]; variables are also known as [[Field (computer science)|fields]], members, attributes, or properties.
Languages that support object-oriented programming (OOP) typically use [[Inheritance (object-oriented programming)|inheritance]] for code reuse and extensibility in the form of either [[Class-based programming|classes]] or [[Prototype-based programming|prototypes]]. Those that use classes support two main concepts:
* [[Class (computer science)|Classes]] – the definitions for the data format and available procedures for a given type or class of object; may also contain data and procedures (known as class methods) themselves, i.e. classes contain the data members and member functions
* [[Object (computer science)|Objects]] – instances of classes
 
Objects can contain other objects in their instance variables; this is known as [[object composition]]. For example, an object in the Employee class might contain (either directly or through a pointer) an object in the Address class, in addition to its own instance variables like "first_name" and "position". Object composition is used to represent "has-a" relationships: every employee has an address, so every Employee object has access to a place to store an Address object (either directly embedded within itself or at a separate ___location addressed via a pointer).
Objects sometimes correspond to things found in the real world. For example, a graphics program may have objects such as "circle", "square", and "menu". An online shopping system might have objects such as "shopping cart", "customer", and "product".<ref>{{cite book|last=Booch|first=Grady|title=Software Engineering with Ada|year=1986|publisher=Addison Wesley|isbn=978-0-8053-0608-8|page=220|url=https://en.wikiquote.org/wiki/Grady_Booch|quote=Perhaps the greatest strength of an object-oriented approach to development is that it offers a mechanism that captures a model of the real world.}}</ref> Sometimes objects represent more abstract entities, like an object that represents an open file, or an object that provides the service of translating measurements from U.S. customary to metric.
 
===Inheritance===
LanguagesOOP thatlanguages supportare object-orienteddiverse, programmingbut typically (OOP) typicallylanguages useallow [[Inheritance (object-oriented programming)|inheritance]] for code reuse and extensibility in the form of either [[Class-basedclass programming(computer science)|classes]] or [[Prototype-based programming|prototypes]]. ThoseThese thatforms useof classesinheritance supportare twosignificantly maindifferent, but analogous terminology is used to define the concepts: of ''object'' and ''instance''.
 
In [[class-based programming]], the most popular style, each object is required to be an [[instance (computer science)|instance]] of a particular ''class''. The class defines the data format or [[data type|type]] (including member variables and their types) and available procedures (class methods or member functions) for a given type or class of object. Objects are created by calling a special type of method in the class known as a [[Constructor (object-oriented programming)|constructor]]. Classes may inherit from other classes, so they are arranged in a hierarchy that represents "is-a-type-of" relationships. For example, class Employee might inherit from class Person. All the data and methods available to the parent class also appear in the child class with the same names. For example, class Person might define variables "first_name" and "last_name" with method "make_full_name()". These will also be available in class Employee, which might add the variables "position" and "salary". It is guaranteed that all instances of class Employee will have the same attributes, such as the name, position, and salary. Procedures and variables can be specific to either the class or the instance; this leads to the following terms:
 
Each object is said to be an [[instance (computer science)|instance]] of a particular class (for example, an object with its name field set to "Mary" might be an instance of class Employee). Procedures in object-oriented programming are known as [[Method (computer science)|methods]]; variables are also known as [[Field (computer science)|fields]], members, attributes, or properties. This leads to the following terms:
* [[Class variable]]s – belong to the ''class as a whole''; there is only one copy of each variable, shared across all instances of the class
* [[Instance variable]]s or attributes – data that belongs to individual ''objects''; every object has its own copy of each one
Line 104 ⟶ 106:
* Instance methods – belong to ''individual objects'', and have access to instance variables for the specific object they are called on, inputs, and class variables
 
SubclassesDepending canon the definition of the language, subclasses may or may not be able to override the methods defined by superclasses. [[Multiple inheritance]] is allowed in some languages, though this can make resolving overrides complicated. Some languages have special support for other concepts like [[Trait (computer programming)|traits]] and [[mixin]]s, 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, class UnicodeConversionMixin might provide a method unicode_to_ascii() when included in class FileReader and class WebPageScraper, which do not share a common parent.
Objects are accessed somewhat like variables with complex internal structures, and in many languages are effectively [[Pointer (computer programming)|pointers]], serving as actual references to a single instance of said object in memory within a heap or stack. They provide a layer of [[Abstraction (computer science)|abstraction]] which can be used to separate internal from external code. External code can use an object by calling a specific instance method with a certain set of input parameters, reading an instance variable, or writing to an instance variable. Objects are created by calling a special type of method in the class known as a [[Constructor (object-oriented programming)|constructor]]. A program may create many instances of the same class as it runs, which operate independently. This is an easy way for the same procedures to be used on different sets of data.
 
[[Abstract class]]es cannot be instantiated into objects; they exist only for inheritance into other "concrete" classes that can be instantiated. In Java, the <code>[[final (Java)|final]]</code> keyword can be used to prevent a class from being subclassed.{{sfn|Bloch|2018|loc=Chapter §2 Item 4 Enforce noninstantiability with a private constructor|p=19}}
Object-oriented programming that uses classes is sometimes called [[class-based programming]], while [[prototype-based programming]] does not typically use classes. As a result, significantly different yet analogous terminology is used to define the concepts of ''object'' and ''instance''.
 
In contrast, in [[Prototype-based programming|prototype-based languagesprogramming]] the, ''objects'' are the primary entities. NoGenerally, ''classes''the concept of a "class" does not even exist. TheRather, the ''prototype'' or ''parent'' of an object is just another object to which the object is linked. EveryIn Self, an object may have multiple or no parents,<ref>{{cite book |chapter= Classifying prototype-based programming languages|chapter-url=https://www.lirmm.fr/~dony/postscript/proto-book.pdf|first1=C|last1=Dony|first2=J|last2=Malenfant|first3=D|last3=Bardon|title=Prototype-based programming: concepts, languages and applications |date=1999 |publisher=Springer |___location=Singapore Berlin Heidelberg |isbn=9789814021258}}</ref> but in the most popular prototype-based language, Javascript, every object has one ''prototype'' link (and only one). New objects can be created based on already existing objects chosen as their prototype. You may call two different objects ''apple'' and ''orange'' a fruit if the object ''fruit'' exists, and both ''apple'' and ''orange'' have ''fruit'' as their prototype. The idea of the ''fruit'' class does not exist explicitly, but can be modeled as the [[equivalence class]] of the objects sharing the same prototype., Theor attributesas andthe methodsset of theobjects ''prototype''satisfying area certain interface ([[Delegationduck (object-oriented programming)|delegatedtyping]]). toUnlike allclass-based theprogramming, objectsit ofis thetypically equivalencepossible classin definedprototype-based bylanguages thisto prototype. Thedefine attributes and methods ''owned'' individually by the object may not be shared bywith other objects of the same equivalence class; e.g.for example, the attribute ''sugar_content'' may be unexpectedly not presentdefined in ''apple''. Onlybut [[singlenot inheritance]] can be implemented through the prototype''orange''.
In some languages classes and objects can be composed using other concepts like [[Trait (computer programming)|traits]] and [[mixin]]s.
 
The doctrine of [[composition over inheritance]] advocates implementing has-a relationships using composition instead of inheritance. For example, instead of inheriting from class Person, class Employee could give each Employee object an internal Person object, which it then has the opportunity to hide from external code even if class Person has many public attributes or methods. Some languages like [[Go (programming language)|Go]] do not support inheritance at all. Go states that it is object-oriented,<ref>{{Cite web |url=https://golang.org/doc/faq#Is_Go_an_object-oriented_language |title=Is Go an object-oriented language? |access-date=April 13, 2019 |quote=Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy.}}</ref> and Bjarne Stroustrup, author of C++, has stated that it is possible to do OOP without inheritance.<ref>{{cite conference |last1=Stroustrup |first1=Bjarne |title=Object-Oriented Programming without Inheritance (Invited Talk) |date=2015 |doi=10.4230/LIPIcs.ECOOP.2015.1|url=https://www.youtube.com/watch?v=xcpSLRpOMJM|conference=29th European Conference on Object-Oriented Programming (ECOOP 2015)|at=1:34}}</ref> [[Delegation (object-oriented programming)|Delegation]] is another language feature that can be used as an alternative to inheritance.
===Class-based vs prototype-based===
In [[Class-based programming|class-based languages]] the ''classes'' are defined beforehand and the ''objects'' are instantiated based on the classes. If two objects ''apple'' and ''orange'' are instantiated from the class ''Fruit'', they are inherently fruits and it is guaranteed that you may handle them in the same way; e.g. a programmer can expect the existence of the same attributes such as ''color'' or ''sugar_content'' or ''is_ripe''.
 
In [[Prototype-based programming|prototype-based languages]] the ''objects'' are the primary entities. No ''classes'' even exist. The ''prototype'' of an object is just another object to which the object is linked. Every object has one ''prototype'' link (and only one). New objects can be created based on already existing objects chosen as their prototype. You may call two different objects ''apple'' and ''orange'' a fruit if the object ''fruit'' exists, and both ''apple'' and ''orange'' have ''fruit'' as their prototype. The idea of the ''fruit'' class does not exist explicitly but as the [[equivalence class]] of the objects sharing the same prototype. The attributes and methods of the ''prototype'' are [[Delegation (object-oriented programming)|delegated]] to all the objects of the equivalence class defined by this prototype. The attributes and methods ''owned'' individually by the object may not be shared by other objects of the same equivalence class; e.g. the attribute ''sugar_content'' may be unexpectedly not present in ''apple''. Only [[single inheritance]] can be implemented through the prototype.
 
===Dynamic dispatch/message passing===
It is the responsibility of the object, not any external code, to select the procedural code to execute in response to a method call, typically by looking up the method at run time in a table associated with the object. This feature is known as [[dynamic dispatch]]. If the call variability relies on more than the single type of the object on which it is called (i.e. at least one other parameter object is involved in the method choice), one speaks of [[multiple dispatch]]. A method call is also known as ''[[message passing]]''. It is conceptualized as a message (the name of the method and its input parameters) being passed to the object for dispatch.
 
Dispatch interacts with inheritance; if a method is not present in a given object or class, the dispatch is [[Delegation (object-oriented programming)|delegated]] to its parent object or class, and so on, going up the chain of inheritance.
A method call is also known as ''[[message passing]]''. It is conceptualized as a message (the name of the method and its input parameters) being passed to the object for dispatch.
 
===Data abstraction and encapsulation===
Data [[Abstraction (computer science)|abstraction]] is a design pattern in which data are visible only to semantically related functions, to prevent misuse. The success of data abstraction leads to frequent incorporation of [[Information hiding|data hiding]] as a design principle in object-oriented and pure functional programming. Similarly, [[Encapsulation (computer programming)|encapsulation]] prevents external code from being concerned with the internal workings of an object. This facilitates [[code refactoring]], for example allowing the author of the class to change how objects of that class represent their data internally without changing any external code (as long as "public" method calls work the same way). It also encourages programmers to put all the code that is concerned with a certain set of data in the same class, which organizes it for easy comprehension by other programmers. Encapsulation is a technique that encourages [[Coupling (computer programming)|decoupling]].
 
LanguagesIn thatobject support classes almost always support [[inheritance (object-oriented programming)|inheritance]]., Thisobjects allowsprovide classesa tolayer bewhich arrangedcan inbe aused hierarchyto thatseparate representsinternal "is-a-type-of"from relationships.external Forcode example,and classimplement Employeeabstraction mightand inheritencapsulation. fromExternal classcode Person.can Allonly theuse dataan andobject methodsby availablecalling toa thespecific parentinstance classmethod alsowith appeara incertain theset childof classinput withparameters, thereading samean names.instance For examplevariable, classor Personwriting mightto definean variablesinstance "first_name"variable. andA "last_name"program withmay methodcreate "make_full_name()".many Theseinstances willof alsoobjects beas availableit in class Employeeruns, which might add the variables "position" andoperate "salary"independently. This technique allows easy re-use of the same procedures and data definitions for different sets of data, in addition to potentially mirroring real-world relationships intuitively. Rather than utilizing database tables and programming subroutines, the developer utilizes objects the user may be more familiar with: objects from their application ___domain.<ref>{{cite book|last=Jacobsen|first=Ivar|title=Object Oriented Software Engineering|year=1992|publisher=Addison-Wesley ACM Press|isbn=978-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>
If a class does not allow calling code to access internal object data and permits access through methods only, this is a form of information hiding known as [[Abstraction (computer science)|abstraction]]. Some languages (Java, for example) let classes enforce access restrictions explicitly, for example, denoting internal data with the <code>private</code> keyword and designating methods intended for use by code outside the class with the <code>public</code> keyword.{{sfn|Bloch|2018|loc=Chapter §4 Item15 Minimize the accessibility of classes and members|pp=73-77}} Methods may also be designed public, private, or intermediate levels such as <code>protected</code> (which allows access from the same class and its subclasses, but not objects of a different class).{{sfn|Bloch|2018|loc=Chapter §4 Item15 Minimize the accessibility of classes and members|pp=73-77}} In other languages (like Python) this is enforced only by convention (for example, <code>private</code> methods may have names that start with an [[underscore]]). In C#, Swift & Kotlin languages, <code>internal</code> keyword permits access only to files present in the same assembly, package, or module as that of the class.<ref>{{Cite web |date=2023-01-05 |title=What is Object Oriented Programming (OOP) In Simple Words? – Software Geek Bytes |url=https://softwaregeekbytes.com/object-oriented-programming-simple-words/ |access-date=2023-01-17 |language=en-US}}</ref>
 
If a class does not allow calling code to access internal object data and permits access through methods only, this is also a form of information hiding known as [[Abstraction (computer science)|abstraction]]. Some languages (Java, for example) let classes enforce access restrictions explicitly, for example, denoting internal data with the <code>private</code> keyword and designating methods intended for use by code outside the class with the <code>public</code> keyword.{{sfn|Bloch|2018|loc=Chapter §4 Item15 Minimize the accessibility of classes and members|pp=73-77}} Methods may also be designed public, private, or intermediate levels such as <code>protected</code> (which allows access from the same class and its subclasses, but not objects of a different class).{{sfn|Bloch|2018|loc=Chapter §4 Item15 Minimize the accessibility of classes and members|pp=73-77}} In other languages (like Python) this is enforced only by convention (for example, <code>private</code> methods may have names that start with an [[underscore]]). In C#, Swift & Kotlin languages, <code>internal</code> keyword permits access only to files present in the same assembly, package, or module as that of the class.<ref>{{Cite web |date=2023-01-05 |title=What is Object Oriented Programming (OOP) In Simple Words? – Software Geek Bytes |url=https://softwaregeekbytes.com/object-oriented-programming-simple-words/ |access-date=2023-01-17 |language=en-US}}</ref>
 
In programming languages, particularly object-oriented ones, the emphasis on abstraction is vital. Object-oriented languages extend the notion of type to incorporate data abstraction, highlighting the significance of restricting access to internal data through methods.<ref>{{Cite journal |last1=Cardelli |first1=Luca |last2=Wegner |first2=Peter |date=1985-12-10 |title=On understanding types, data abstraction, and polymorphism |journal=ACM Computing Surveys |language=en |volume=17 |issue=4 |pages=471–523 |doi=10.1145/6041.6042 |issn=0360-0300|doi-access=free }}</ref>
 
===Encapsulation===
 
[[Encapsulation (computer programming)|Encapsulation]] prevents external code from being concerned with the internal workings of an object. This facilitates [[code refactoring]], for example allowing the author of the class to change how objects of that class represent their data internally without changing any external code (as long as "public" method calls work the same way). It also encourages programmers to put all the code that is concerned with a certain set of data in the same class, which organizes it for easy comprehension by other programmers. Encapsulation is a technique that encourages [[Coupling (computer programming)|decoupling]].
 
===Composition, inheritance, and delegation===
Objects can contain other objects in their instance variables; this is known as [[object composition]]. For example, an object in the Employee class might contain (either directly or through a pointer) an object in the Address class, in addition to its own instance variables like "first_name" and "position". Object composition is used to represent "has-a" relationships: every employee has an address, so every Employee object has access to a place to store an Address object (either directly embedded within itself or at a separate ___location addressed via a pointer).
 
Languages that support classes almost always support [[inheritance (object-oriented programming)|inheritance]]. This allows classes to be arranged in a hierarchy that represents "is-a-type-of" relationships. For example, class Employee might inherit from class Person. All the data and methods available to the parent class also appear in the child class with the same names. For example, class Person might define variables "first_name" and "last_name" with method "make_full_name()". These will also be available in class Employee, which might add the variables "position" and "salary". This technique allows easy re-use of the same procedures and data definitions, in addition to potentially mirroring real-world relationships intuitively. Rather than utilizing database tables and programming subroutines, the developer utilizes objects the user may be more familiar with: objects from their application ___domain.<ref>{{cite book|last=Jacobsen|first=Ivar|title=Object Oriented Software Engineering|year=1992|publisher=Addison-Wesley ACM Press|isbn=978-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>
 
Subclasses can override the methods defined by superclasses. [[Multiple inheritance]] is allowed in some languages, though this can make resolving overrides complicated. Some languages have special support for [[mixin]]s, 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, class UnicodeConversionMixin might provide a method unicode_to_ascii() when included in class FileReader and class WebPageScraper, which do not share a common parent.
 
[[Abstract class]]es cannot be instantiated into objects; they exist only for inheritance into other "concrete" classes that can be instantiated. In Java, the <code>[[final (Java)|final]]</code> keyword can be used to prevent a class from being subclassed.{{sfn|Bloch|2018|loc=Chapter §2 Item 4 Enforce noninstantiability with a private constructor|p=19}}
 
The doctrine of [[composition over inheritance]] advocates implementing has-a relationships using composition instead of inheritance. For example, instead of inheriting from class Person, class Employee could give each Employee object an internal Person object, which it then has the opportunity to hide from external code even if class Person has many public attributes or methods. Some languages, like [[Go (programming language)|Go]] do not support inheritance at all.
 
The "[[open/closed principle]]" advocates that classes and functions "should be open for extension, but closed for modification".
 
[[Delegation (object-oriented programming)|Delegation]] is another language feature that can be used as an alternative to inheritance.
 
===Polymorphism===