Object-Oriented Programming (OOP) is a programming language paradigm based on the concept of “objects“, which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods.
A feature of objects is that an object’s procedures can access and often modify the data fields of the object with which they are associated (objects have a notion of “this” or “self“). In OOP, developers design computer programs by creating objects that interact with one another.
OOP languages vary significantly, but most popular ones use a class-based approach. In these languages, classes define objects and typically determine their type.
Many of the most widely used programming languages (such as C++, Object Pascal, Java, Python etc.) are multi-paradigm programming languages that support object-oriented programming to a greater or lesser degree, typically in combination with imperative, procedural programming.
Significant object-oriented languages include Java, C++, C#, Python, PHP, Ruby, Perl, Object Pascal, Objective-C, Dart, Swift, Scala, Common Lisp, and Smalltalk.
The Basic OOP Concepts
If you are new to object-oriented programming languages, you will need to know a few basics before you can get started with code. The following definitions will help you better understand object-oriented programming:
- Abstraction: The process of picking out (abstracting) common features of objects and procedures.
- Class: A category of objects. The class defines all the common properties of the different objects that belong to it.
- Encapsulation: The process of combining elements to create a new entity. A procedure is a type of encapsulation because it combines a series of computer instructions.
- Information hiding: The process of hiding details of an object or function. Information hiding is a powerful programming technique because it reduces complexity.
- Inheritance: a feature that represents the “is a” relationship between different classes.
Interface: the languages and codes that the applications use to communicate with each other and with the hardware. - Messaging: Message passing is a form of communication used in parallel programming and object-oriented programming.
- Object: a self-contained entity that consists of both data and procedures to manipulate the data.
- Polymorphism: A programming language’s ability to process objects differently depending on their data type or class.
- Procedure: a section of a program that performs a specific task.
Advantages of Object Oriented Programming
One of the principal advantages of object-oriented programming techniques over procedural programming techniques is that they enable programmers to create modules that do not need to be changed when a new type of object is added.
A programmer can simply create a new object that inherits many of its features from existing objects. This makes object-oriented programs easier to modify.
OOPL – Object-Oriented Programming Languages
An object-oriented programming language (OOPL) is a high-level programming language based on the object-oriented model. To perform object-oriented programming, one needs an object-oriented programming language.
Many modern programming languages are object-oriented, however, some older programming languages, such as Pascal, do offer object-oriented versions. Examples of object-oriented programming languages include Java, C++ and Smalltalk.
The First OOPL
Simula, developed in the 1960s at the Norwegian Computing Center in Oslo, is considered to be the first object-oriented programming language. Despite being first, Smalltalk is considered to be the only true object-oriented programming environment and the one against which all others must be compared. It was first developed for educational use at Xerox Corporation’s Palo Alto Research Center in the late 1960s and released in 1972.
Features
Object-oriented programming uses objects, but not all of the associated techniques and structures are supported directly in languages that claim to support OOP. The features listed below are, however, common among languages considered strongly class- and object-oriented (or multi-paradigm with OOP support), with notable exceptions mentioned.
Variables that can store information formatted in a small number of built-in data types like integers and alphanumeric characters. This may include data structures like strings, lists, and hash tables that are either built-in or result from combining variables using memory pointers
Procedures – also known as functions, methods, routines, or subroutines – that take input, generate output and manipulate data. Modern languages include structured programming constructs like loops and conditionals.
Modular programming support provides the ability to group procedures into files and modules for organizational purposes. Modules are namespaced so identifiers in one module will not be accidentally confused with a procedure or variable sharing the same name in another file or module.
Objects and classes
Languages that support object-oriented programming typically use inheritance for code reuse and extensibility in the form of either classes or prototypes. Those that use classes support two main concepts:
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
Objects: Instances of Classes
Real-World and Abstract Representations
Objects sometimes correspond to real-world entities. For example:
- A graphics program might have objects such as “circle,” “square,” and “menu.”
- An online shopping system could include objects like “shopping cart,” “customer,” and “product.”
Objects can also represent abstract entities, such as:
- An object that represents an open file.
- An object that translates measurements between U.S. customary and metric systems.
Objects and Classes
Each object is an instance of a specific class. For example, an object with its name
field set to "Mary"
could be an instance of the Employee
class.
In object-oriented programming (OOP):
- Procedures are referred to as methods.
- Variables are also known as fields, members, attributes, or properties.
This leads to the following distinctions:
- Class Variables: Belong to the class as a whole, with only one copy shared among all instances.
- Instance Variables or Attributes: Contain data unique to each object, with every object maintaining its own copy.
- Member Variables: A general term referring to both class and instance variables defined by a class.
- Class Methods: Belong to the class as a whole and can only access class variables and procedure inputs.
- Instance Methods: Belong to specific objects and can access instance variables, class variables, and inputs.
Object Behavior and Access
Objects behave like variables with a complex internal structure. In many programming languages, objects are effectively pointers, serving as references to specific instances in memory. These references typically reside in the heap or stack.
Objects provide a layer of abstraction, separating internal functionality from external access. External code can:
- Call a specific instance method with input parameters.
- Read an instance variable.
- Write to an instance variable.
Creating and Managing Objects
Objects are created using a constructor, a special method in the class. A program may create many instances of the same class during runtime. These instances operate independently, allowing the same procedures to be applied to different sets of data.
Class-Based vs. Prototype-Based Programming
Object-oriented programming that uses classes is referred to as class-based programming. In contrast, prototype-based programming does not typically use classes. Instead, it relies on significantly different yet analogous terminology to define objects and instances.
Additional Composition Features
In some languages, classes and objects can incorporate concepts like traits and mixins to extend functionality and enhance code reuse.
Object-Oriented Programming (OOP) – Class definition, and instances.
Class-based vs prototype-based
In 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 colour or sugar content or is ripe.
In 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 doesn’t exist explicitly, but as the equivalence class of the objects sharing the same prototype. The attributes and methods of the prototype are 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 attributes sugar content may be unexpectedly not present in apple. Only single inheritance can be implemented through the prototype.
Lets create some code. Lets talk some OOP (Object Oriented Programming.) I’m gonna drop my new album on you… :-)
You down wit OOP ?
You down wit OOP ? yeah you know me
Fun Aside: Back to the Keyboard
After you finish with your clock chain necklace and booty bouncing, let’s get back to the keyboard. Enough fun and games.
Game Development Example: A Hypothetical GTA-Style Game
The Role of Car Classes
Hypothetically, let’s say we are making a video game similar to GTA (Grand Theft Auto). In game development, having multiple car classes adds variety and complexity. For instance, cars like the Progen Emerus and Declasse Scramjet can represent distinct vehicle classes.
Designing a system with 50 or more potential car classes may seem complex, especially when creating numerous instances of each class.
Scaling Complexity: Cars and Citizens
Imagine a large urban environment, such as Los Angeles, with a population of approximately 3.8 million people. Each citizen could potentially own one or more cars from the 50 available classes.
If every citizen owns one car from each class, the total number of cars in the game world would be staggering, demonstrating the need for efficient class and instance management.
Understanding Classes in Object-Oriented Programming
The Purpose of a Class
A class organizes information about a type of data, enabling programmers to reuse elements when creating multiple instances of that data type. For example, if a programmer wanted to create three car instances—a BMW, a Ferrari, and a Ford—they could use a single Car
class.
The Car
class allows the programmer to store shared information (like color, model, and make) while associating unique attributes with each instance.
Classes as Blueprints for Objects
In object-oriented programming, a class serves as a blueprint for creating objects (a specific data structure). It defines:
- Initial values for state (member variables or attributes).
- Behavior implementations (member functions or methods).
Using the class keyword, developers define classes to manage objects. An instance is a specific object created from a class. For example, an individual car, such as a red BMW, represents an instance of the Car
class.
Key Features of Classes
Code Reusability Through Inheritance
Classes not only manage objects but also support inheritance, which allows programmers to reuse code. Inheritance is a key component of object-oriented programming, enabling efficient management of related objects while reducing redundancy.
The image above shows how a Car object can be the template for many other Car instances. In the image, there are three instances: polo, mini, and beetle.
Here, we will make a new class called Car, that will structure a Car object to contain information about the car’s model, the color, how many passengers it can hold, its speed, etc. A class can define types of operations, or methods, that can be performed on a Car object.
For example, the Car class might specify an accelerate method, which would update the speed attribute of the car object.
For example, the Car class might specify an accelerate method, which would update the speed attribute of the car object.
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 runtime in a table associated with the object. This feature is known as dynamic dispatch and distinguishes an object from an abstract data type (or module), which has a fixed (static) implementation of the operations for all instances. If there are multiple methods that might be run for a given name, it is known as multiple dispatches.
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.
Encapsulation
is an object-oriented programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding.
If a class does not allow calling code to access internal object data and permits access through methods only, this is a strong form of abstraction or information hiding known as encapsulation. Some languages (Java, for example) let classes enforce access restrictions explicitly, for example denoting internal data with the private keyword and designating methods intended for use by code outside the class with the public keyword.
Developers can design methods as public, private, or at intermediate levels like protected. Protected methods allow access from the same class and its subclasses but block access from objects of a different class. In some languages, such as Python, conventions enforce this distinction. For instance, developers use an underscore prefix to indicate private methods. Encapsulation ensures that external code does not rely on the internal workings of an object.
This approach simplifies code refactoring. For example, a class author can modify how objects of that class store their data internally without affecting external code, as long as “public” methods behave consistently. Encapsulation also encourages programmers to group all code related to a specific set of data within the same class. This organization improves code readability and comprehension. By design, encapsulation promotes decoupling.
Composition, Inheritance, and Delegation
Object Composition
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 (point to) an object in the Address
class, in addition to its own instance variables like first_name
and position
.
Object composition represents “has-a” relationships. For example, every employee has an address, so every Employee
object has a place to store an Address
object.
Inheritance
Languages that support classes almost always support inheritance. This allows classes to be arranged in a hierarchy that represents “is-a-type-of” relationships. For instance, the Employee
class might inherit from the Person
class. All the data and methods in the parent class also appear in the child class with the same names.
For example, the Person
class might define variables first_name
and last_name
along with the method make_full_name()
. These would also be available in the Employee
class, which might add variables like position
and salary
.
This technique facilitates the reuse of procedures and data definitions, mirroring real-world relationships intuitively. Instead of relying on database tables and subroutines, developers utilize objects that represent domain-specific entities familiar to the user.
Overriding and Mixins
Subclasses can override methods defined by superclasses. Some languages allow multiple inheritance, though resolving overrides in such cases can be complex. Certain languages provide special support for mixins.
In languages with multiple inheritance, a mixin is a class that does not represent an “is-a-type-of” relationship. Mixins add the same methods to multiple classes. For example, a UnicodeConversionMixin
might provide a method unicode_to_ascii()
that can be included in both FileReader
and WebPageScraper
classes, even if they don’t share a common parent.
Abstract Classes and Composition Over Inheritance
Abstract classes cannot be instantiated into objects. They exist solely for inheritance into “concrete” classes that can be instantiated. In Java, the final
keyword prevents a class from being subclassed.
The doctrine of composition over inheritance advocates implementing “has-a” relationships using composition instead of inheritance. For example, instead of inheriting from the Person
class, the Employee
class could give each Employee
object an internal Person
object. This approach allows the developer to hide Person
from external code, even if Person
has many public attributes or methods.
Some languages, like Go, do not support inheritance at all.
Open/Closed Principle and Delegation
The open/closed principle states that classes and functions “should be open for extension but closed for modification.”
Delegation is another feature that can serve as an alternative to inheritance.
Polymorphism
Subtyping, a form of polymorphism, is when calling code can be agnostic as to whether an object belongs to a parent class or one of its descendants. For example, a function might call “make_full_name()” on an object, which will work whether the object is of class Person or class Employee. This is another type of abstraction which simplifies code external to the class hierarchy and enables strong separation of concerns.
Open recursion
In languages that support open recursion, object methods can call other methods on the same object (including themselves), typically using a special variable or keyword called this or self. This variable uses late binding, allowing a method in one class to invoke another method defined later in a subclass.
History of Object-Oriented Programming
Early Concepts and Terminology
The concepts of “objects” and “oriented” in programming emerged at MIT in the late 1950s and early 1960s. By 1960, the artificial intelligence group referred to identified items (LISP atoms) with attributes as “objects.” Alan Kay later acknowledged LISP internals as a significant influence on his thinking in 1966.
Sketchpad, created by Ivan Sutherland in 1960–61, introduced graphical notions of “object” and “instance.” In his 1963 dissertation, Sutherland defined these concepts, with “master” or “definition” representing classes. AED-0, an MIT ALGOL variant, linked data structures (“plexes”) and procedures, anticipating the ideas of messages, methods, and member functions.
The Simula Programming Language
In the 1960s, Simula implemented key object-oriented programming concepts, including classes, objects, inheritance, and dynamic binding. Kristen Nygaard began the Simula project in 1962 at the Norwegian Computing Center, joined later by Ole-Johan Dahl. Originally designed as an ALGOL 60 procedure package, Simula evolved into a standalone programming language. The first Simula version launched in 1964 and gained traction by 1966. A compiler for Simula 67 introduced subclassing and object generation, becoming widely available in 1968.
Expansion and Influence
In the 1970s, the Smalltalk programming language was developed at Xerox PARC by Alan Kay, Dan Ingalls, and Adele Goldberg. Smalltalk pioneered fully dynamic systems, graphical environments, and runtime class creation. Its influence extended to the Lisp community, which integrated object-based techniques in extensions like LOOPS and Flavors, leading to the Common Lisp Object System.
Adoption and Evolution
Smalltalk gained attention in 1981 through Byte Magazine and inspired languages like Objective-C and C++, which combined Simula concepts with existing paradigms. Eiffel, designed in 1985 by Bertrand Meyer, focused on software quality with its “Design by Contract” reliability mechanism.
The Rise of Object-Oriented Programming
The 1990s saw object-oriented programming become dominant, supported by languages like C++, Visual FoxPro, and Delphi. The widespread adoption of graphical user interfaces reinforced OOP’s relevance. Java, C#, and VB.NET further popularized OOP, with features like cross-language inheritance and dynamic libraries enhancing their appeal.
Object-Oriented Additions to Existing Languages
Many procedural languages, such as Ada, BASIC, Fortran, Pascal, and COBOL, adopted object-oriented features. However, these additions sometimes caused compatibility and maintainability challenges. Languages like Python and Ruby emerged with primary support for OOP while maintaining procedural compatibility.
OOP languages
Simula (1967) is generally accepted as being the first language with the primary features of an object-oriented language. Developers created it to make simulation programs, where objects became the most important form of information representation. Smalltalk (1972 to 1980) is another early example and played a key role in developing much of the theory of OOP. Regarding the degree of object orientation, the following distinctions apply:
Languages called “pure” OO languages, because everything in them is treated consistently as an object, from primitives such as characters and punctuation, all the way up to whole classes, prototypes, blocks, modules, etc. They were designed specifically to facilitate, even enforce, OO methods. Examples: Python, Ruby, Scala, Smalltalk, Eiffel, Emerald, JADE, Self.
Languages designed mainly for OO programming, but with some procedural elements. Examples: Java, C++, C#, Delphi/Object Pascal, VB.NET.
Languages that are historically procedural languages, but have been extended with some OO features. Examples: PHP, Perl, Visual Basic (derived from BASIC), MATLAB, COBOL 2002, Fortran 2003, ABAP, Ada 95, Pascal.
Languages with most of the features of objects (classes, methods, inheritance), but in a distinctly original form. Examples: Oberon (Oberon-1 or Oberon-2).
Languages with abstract data type support which may be used to resemble OO programming, but without all features of object-orientation. This includes object-based and prototype-based languages. Examples: JavaScript, Lua, Modula-2, CLU.
Chameleon languages that support multiple paradigms, including OO. Tcl stands out among these for TclOO, a hybrid object system that supports both prototype-based programming and class-based OO.
OOP in dynamic languages
In recent years, object-oriented programming has become especially popular in dynamic programming languages. Python, PowerShell, Ruby and Groovy are dynamic languages built on OOP principles, while Perl and PHP have been adding object-oriented features since Perl 5 and PHP 4, and ColdFusion since version 6.
The Document Object Model of HTML, XHTML, and XML documents on the Internet has bindings to the popular JavaScript/ECMAScript language. JavaScript is perhaps the best known prototype-based programming language, which employs cloning from prototypes rather than inheriting from a class (contrast to class-based programming). Another scripting language that takes this approach is Lua.
OOP in a network protocol
The messages that flow between computers to request services in a client-server environment can be designed as the linearizations of objects defined by class objects known to both the client and the server. For example, a simple linearized object would consist of a length field, a code point identifying the class, and a data value. A more complex example would be a command consisting of the length and code point of the command and values consisting of linearized objects representing the command’s parameters.
The server must direct each command to an object whose class (or superclass) recognizes the command and provides the requested service. Developers typically model clients and servers as complex object-oriented structures. Distributed Data Management Architecture (DDM) took this approach and used class objects to define objects at four levels of a formal hierarchy:
Fields defining the data values that form messages, such as their length, codepoint and data values.
Objects and collections of objects resemble those found in a Smalltalk program for messages and parameters.
Managers similar to AS/400 objects, such as a directory to files and files consisting of metadata and records. Managers conceptually provide memory and processing resources for their contained objects.
A client or server consisting of all the managers necessary to implement a full processing environment, supporting such aspects as directory services, security and concurrency control. The initial version of DDM defined distributed file services. It was later extended to be the foundation of Distributed Relational Database Architecture (DRDA).
Design patterns
Challenges of object-oriented design are addressed by several methodologies. Most common is known as the design patterns codified by Gamma et al.. More broadly, the term “design patterns” can be used to refer to any general, repeatable solution to a commonly occurring problem in software design. Some of these commonly occurring problems have implications and solutions particular to object-oriented development.
Inheritance and behavioural subtyping
It is intuitive to assume that inheritance creates a semantic “is a” relationship, and thus to infer that objects instantiated from subclasses can always be safely used instead of those instantiated from the superclass. This intuition is unfortunately false in most OOP languages, in particular in all those that allow mutable objects. Subtype polymorphism as enforced by the type checker in OOP languages (with mutable objects) cannot guarantee behavioural subtyping in any context. Behavioral subtyping is undecidable in general, making it impossible for a program (compiler) to implement. Developers must carefully design class or object hierarchies to account for potential incorrect uses that syntax checks cannot detect. This issue is known as the Liskov substitution principle.
The following patterns:
Creational patterns: Factory method pattern, Abstract factory pattern, Singleton pattern, Builder pattern, Prototype pattern
Structural patterns: Adapter pattern, Bridge pattern, Composite pattern, Decorator pattern, Facade pattern, Flyweight pattern, Proxy pattern
Behavioral patterns: Chain-of-responsibility pattern, Command pattern, Interpreter pattern, Iterator pattern, Mediator pattern, Memento pattern, Observer pattern, State pattern, Strategy pattern, Template method pattern, Visitor pattern
Object-orientation and databases
Both object-oriented programming and relational database management systems (RDBMSs) are extremely common in software today. Since relational databases don’t store objects directly (though some RDBMSs have object-oriented features to approximate this), there is a general need to bridge the two worlds. Developers refer to the challenge of bridging object-oriented programming accesses and data patterns with relational databases as object-relational impedance mismatch. There are a number of approaches to cope with this problem, but no general solution without downsides. One of the most common approaches is object-relational mapping, as found in IDE languages such as Visual FoxPro and libraries such as Java Data Objects and Ruby on Rails’ ActiveRecord.
Developers can use object databases to replace RDBMSs, but these alternatives have achieved less technical and commercial success.
Real-world modelling and relationships
Developers use OOP to associate real-world objects and processes with digital counterparts. However, some disagree about whether OOP effectively facilitates real-world mapping or whether such mapping is a worthwhile goal. In Object-Oriented Software Construction, Bertrand Meyer argues that a program models a part of the world rather than the world itself, stating, “Reality is a cousin twice removed.”
At the same time, experts have highlighted significant limitations of OOP. For instance, the circle-ellipse problem presents challenges when using OOP’s inheritance concept.
Niklaus Wirth, known for Wirth’s law (“Software is getting slower more rapidly than hardware becomes faster”), offered a different perspective. In his paper Good Ideas through the Looking Glass, Wirth wrote, “This paradigm closely reflects the structure of systems ‘in the real world,’ and it is therefore well suited to model complex systems with complex behaviours”—a contrast to the KISS principle.
Steve Yegge and others observed that natural languages do not strictly prioritize things (objects/nouns) before actions (methods/verbs), as OOP does. This difference can lead OOP to produce more convoluted solutions compared to procedural programming.
OOP and control flow
Developers created OOP to improve the reusability and maintainability of source code.
The transparent representation of the control flow did not take priority, as the compiler was responsible for handling it.
With the increasing relevance of parallel hardware and multithreaded coding, developing transparent control flow becomes more important, something hard to achieve with OOP.
Responsibility- vs. data-driven design
Responsibility-driven design defines classes based on a contract. A class focuses on its responsibilities and the information it shares.
Wirfs-Brock and Wilkerson contrast this with data-driven design, where developers define classes based on the data structures they need to manage. The authors hold that responsibility-driven design is preferable.
Criticism of Object-Oriented Programming
Concerns About Reusability and Modularity
Critics have raised several concerns about the OOP paradigm. They argue that it fails to meet its stated goals of reusability and modularity. Additionally, they claim it overemphasizes data and objects in software design and modeling, neglecting other crucial aspects like computation and algorithms.
Efficiency and Complexity
Luca Cardelli has claimed that OOP code is “intrinsically less efficient” than procedural code, that OOP can take longer to compile, and that OOP languages have “extremely poor modularity properties with respect to class extension and modification” and tend to be extremely complex.
Joe Armstrong, the principal inventor of Erlang, emphasizes this point, stating:
The problem with object-oriented languages is they’ve got all this implicit environment that they carry around with them. You wanted a banana but what you got were a gorilla holding the banana and the entire jungle.
A study by Potok et al. showed no significant difference in productivity between OOP and procedural approaches.
Lack of Rigorous Definition
Christopher J. Date stated that critically comparing OOP to other technologies, particularly relational ones, is difficult due to the lack of an agreed-upon and rigorous definition of OOP. However, Date and Darwen proposed a theoretical foundation that uses OOP as a customizable type system to support RDBMS.
Criticisms of Complexity and Utility
In an article, Lawrence Krubner claimed that compared to other languages (LISP dialects, functional languages, etc.), OOP languages have no unique strengths and impose a heavy burden of unnecessary complexity.
Alexander Stepanov criticized OOP for its technical and philosophical limitations:
I find OOP technically unsound. It attempts to decompose the world in terms of interfaces that vary on a single type. To deal with the real problems, you need multi-sorted algebras — families of interfaces that span multiple types. I find OOP philosophically unsound. It claims that everything is an object. Even if it is true, it is not very interesting — saying that everything is an object is saying nothing at all.
Popularity and Mediocrity
Paul Graham suggested that OOP’s popularity within large companies stems from “large (and frequently changing) groups of mediocre programmers.” According to Graham, OOP’s discipline prevents any single programmer from “doing too much damage.”
Noun-First Perspective
Steve Yegge observed that OOP prioritizes nouns over verbs, contrasting it with functional programming:
Object-Oriented Programming puts the Nouns first and foremost. Why would you go to such lengths to put one part of speech on a pedestal? Why should one kind of concept take precedence over another? It’s not as if OOP has suddenly made verbs less important in the way we actually think. It’s a strangely skewed perspective.
Limitations in Modeling Real-World Systems
Rich Hickey, the creator of Clojure, described object systems as overly simplistic models of the real world. He emphasized OOP’s inability to model time properly, a limitation that becomes increasingly problematic as software systems grow more concurrent.
Overhead and Transparency Issues
Eric S. Raymond, a Unix programmer and open-source software advocate, criticized OOP for encouraging thickly layered programs that lack transparency. He compared this unfavorably to Unix and the C programming language, which prioritize simplicity and transparency.
Focus on Types Over Data Structures
Rob Pike, a key contributor to UTF-8 and Go, described object-oriented programming as “the Roman numerals of computing.” He argued that OOP languages often shift focus away from data structures and algorithms to types. Pike shared an example of a Java professor who proposed creating six new classes for a problem instead of using a simple lookup table.
Formal semantics
Objects are the run-time entities in an object-oriented system. They may represent a person, a place, a bank account, a table of data, or any item that the program has to handle.
There have been several attempts at formalizing the concepts used in object-oriented programming. Various concepts and constructs interpret OOP principles.
- coalgebraic data types
- abstract data types (which have existential types) allow the definition of modules but these do not support dynamic dispatch
- recursive types
- encapsulated state
- inheritance
- Records provide a foundation for understanding objects when developers store function literals in fields, as observed in functional programming languages. However, developers must design more complex calculi to incorporate essential features of object-oriented programming (OOP). Several extensions of System F<: that deal with mutable objects have been studied; these allow both subtype polymorphism and parametric polymorphism (generics)
Attempts to find a consensus definition or theory behind objects have not proven very successful (however, see Abadi & Cardelli, A Theory of Objects for formal definitions of many OOP concepts and constructs), and often diverge widely. For example, some definitions focus on mental activities, and some on program structuring. One of the simpler definitions is that OOP is the act of using “map” data structures or arrays that can contain functions and pointers to other maps, all with some syntactic and scoping sugar on top. Inheritance occurs when a program clones maps, a process sometimes referred to as “prototyping.”
Object-Oriented Programming (OOP) and Its Principles
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “objects”, which can contain data, in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods). OOP aims to incorporate the principles of real-world objects into programming, allowing for a more intuitive way to handle complex software projects. The core principles of OOP are:
- Polymorphism: This principle enables treating objects of different classes as if they belong to a common superclass. Developers use polymorphism to write the same code for different types of objects, allowing it to produce varying outcomes. Method overriding achieves polymorphism by letting a child class implement a method differently from its parent class. Method overloading offers another approach, where two methods share the same name but differ in their parameters.
- Abstraction: This principle involves hiding complex implementation details and showing only the necessary features of an object. It can reduce programming complexity and increase efficiency.
- Encapsulation: This principle is about bundling the data (attributes) and methods that operate on the data into a single unit called an object. It also involves restricting access to the inner workings of that object (data hiding), which can prevent accidental modification of data.
- Inheritance: This allows a class to inherit properties and methods from another class. A child or subclass inherits from a parent or superclass. Inheritance promotes code reusability and can make code more organized and manageable.
Sample Python Code Demonstrating OOP Principles
Let’s create a simple Python example to demonstrate these principles:
In this example:
- Encapsulation: is demonstrated by encapsulating the
name
attribute in theAnimal
class. - Inheritance: is shown where the
Dog
andCat
classes inherit from theAnimal
class. - Polymorphism: is shown in how both
Dog
andCat
classes can use thespeak
method but implement it differently. - Abstraction: is shown by defining a method
speak
in theAnimal
class, which is then implemented by its subclasses. TheAnimal
class cannot be instantiated on its own because it contains aspeak
method that is not implemented, making it abstract in nature.
This code provides a simple yet comprehensive demonstration of the key OOP principles, making it a good starting point for learners.
Here’s how the OOP concepts would look in a code-like format without using any special formatting:
1. Encapsulation
Class Car:
Property speed
Method accelerate():
Increase speed by 2
Once a Car is created:
Set speed to 0
Create a Car object
bmw = Car()
bmw.accelerate()
2. Abstraction
Class Car:
Hide internal details of accelerate()
Method drive():
Call accelerate() and handle other actions
Create a Car object
bmw = Car()
bmw.drive()
3. Inheritance
Class Car:
Property speed
Method accelerate()
Class ElectricCar inherits from Car:
Property battery_level
Create an ElectricCar object
tesla = ElectricCar()
tesla.accelerate()
4. Polymorphism
Class Car:
Method horn():
Print “Regular car horn sound”
Class Truck inherits from Car:
Override horn():
Print “Loud truck horn sound”
Create a Car object and a Truck object
bmw = Car()
truck = Truck()
bmw.horn() # Prints “Regular car horn sound”
truck.horn() # Prints “Loud truck horn sound”
Full Example (Combining All Concepts)
Class Vehicle:
Method start():
Print “Vehicle is starting”
Class Car inherits from Vehicle:
Property speed
Property color
Method accelerate()
Class Motorcycle inherits from Vehicle:
Override start():
Print “Motorcycle is roaring to life”
Create Car and Motorcycle objects
bmw = Car()
motorcycle = Motorcycle()
bmw.start() # Prints “Vehicle is starting”
motorcycle.start() # Prints “Motorcycle is roaring to life”
To demonstrate Object-Oriented Programming (OOP) concepts effectively, I’ll write a complete Python example that implements these ideas clearly. Here’s how these concepts can be realized:
Full Python Code Example
Key Features:
- Encapsulation: The
__speed
attribute in theCar
class is private and accessed using public methods. - Abstraction: The
AdvancedCar
class hides the details of how the car accelerates and combines actions in thedrive
method. - Inheritance: The
ElectricCar
class inherits fromCar
and adds additional functionality with acharge_battery
method. - Polymorphism: The
start
method behaves differently forMotorcycle
andVehicle
. Thehorn
method inTruck
overrides behavior inCar
.