Basic concepts and principles of OOP. Object Oriented Programming (OOP) Stands for OOP

The concept of object-oriented programming (OOP) appeared more than forty years ago, as a development of the ideas of procedural programming. The ideology of procedural programming, in my opinion, is nothing special: all programs are represented by a set of procedures and functions, while the procedures and functions themselves are sequences of statements, the execution of which modifies the values ​​of variables in memory. The main program in procedural programming is also a procedure (function), the body of which may contain calls to other procedures and functions - subroutines. The essence of procedural programming is simple: data is separate, behavior is separate. I tried to collect what structures are included in it in a separate section. Dividing the code into subroutines, firstly, allows, and secondly,.

The ideology of object-oriented programming, as the name suggests, is built around the concept of object. An object combines both data and behavior. An object is any entity that the program deals with, namely: domain objects modeled by the program; operating system resources; network protocols and much more. In essence, an object is the same, but supplemented with procedures and functions that control the elements of this structure. For example, in a procedural programming language, a variable would be created separately to store the file name and separately to store its descriptor (a unique resource identifier in the operating system), as well as a number of procedures for working with the file: open the file, read data from the file and close the file . All these procedures, in addition to the usual parameters and variables for storing the result, would be required to accept the same descriptor in order to understand which file we are talking about. In an object-oriented language, for the same purpose, a file object would be described, which would also store a name and a handle within itself and provide the user with procedures for opening, reading and closing itself (the file associated with a specific object). The difference would be that the handle would be hidden from the rest of the program, created in the file open routine code, and used only implicitly by the object itself. Thus, the user of the object (the program code of the program external to the object) would not need to pass the handle each time in procedure parameters. An object is a set of data and methods for working with this data, some of which may be hidden from the world around it, which includes implementation details. The terminology of object-oriented programming will be discussed in more detail below.

In an object-oriented programming language, almost everything is an object, with the exception of statements: and are objects, and an error description is an object, and, finally, the main program is also an object. It remains to understand what an object is from the point of view of the program itself, how it is created and used. The second fundamental concept of OOP is the class. A class is a new data type compared to procedural programming, the instances of which are called objects. A class, as already mentioned, is similar to a compound data type or structure, but supplemented with procedures and functions (methods) for working with its data. Now is the time to describe the basic terms of object-oriented programming.

Object-Oriented Programming Terminology

Before moving on to describe the benefits that OOP gives to software developers in the process and software products, it is necessary to become familiar with the most commonly used terms in this area.

Class – a data type that describes the structure and behavior of objects.

An object – an instance of a class.

Field – class data element: a variable of an elementary type, structure, or other class that is part of a class.

Object state – a set of current object field values.

Method – a procedure or function that executes in the context of the object on which it is called. Methods can change the state of the current object or the state of objects passed to them as parameters.

Property – a special type of methods designed to modify individual fields of an object. The names of the properties are usually the same as the names of the corresponding fields. Externally, working with properties looks exactly the same as working with fields of a structure or class, but in fact, before returning or assigning a new value to a field, program code can be executed that performs various types of checks, for example, checking whether the new value is valid .

Class member – fields, methods and properties of the class.

Access modifier – an additional characteristic of class members that determines whether they are accessible from an external program, or whether they are used exclusively within the boundaries of the class and hidden from the outside world. Access modifiers separate all members of a class into implementation details and a public or partially public interface.

Constructor – a special method executed immediately after creating an instance of a class. The constructor initializes the fields of the object - brings the object to its initial state. Constructors can be either with or without parameters. A constructor without parameters is called a default constructor, which can only have one. The name of the constructor method most often coincides with the name of the class itself.

Destructor – a special method called by the program execution environment at the moment when an object is removed from RAM. The destructor is used in cases where the class includes resources that require explicit release (files, database connections, network connections, etc.)

Interface – a set of methods and properties of an object that are publicly available and designed to solve a certain range of problems, for example, an interface for generating a graphical representation of an object on the screen or an interface for saving the state of an object in a file or database.

Static member – any element of a class that can be used without creating a corresponding object. For example, if a class method does not use a single field, but works exclusively with the parameters passed to it, then nothing prevents it from being used in the context of the entire class, without creating separate instances of it. Constants in the context of a class are usually always static members of the class.

This is not all with OOP terminology, but other concepts associated with this paradigm will be discussed in the next section.

Benefits of Object-Oriented Programming

Now let's talk about the properties that a program acquires when using an object-oriented approach to its design and coding. It seems to me that most of these properties are advantages of OOP, but there are other opinions on this matter...

    Encapsulation denotes hiding the implementation details of a class by rewarding individual members with appropriate access modifiers. Thus, all the functionality of an object aimed at interacting with other program objects is grouped into an open interface, and the details are carefully hidden inside, which saves the main business logic code from things it does not need. Encapsulation improves the reliability of your code because it ensures that certain data cannot be changed outside the containing class.

    Inheritance. The cornerstone of OOP. In object-oriented programming, it is possible to inherit the structure and behavior of a class from another class. The class from which they inherit is called a base or superclass, and the class that is obtained as a result of inheritance is called a derived or simply a descendant. Any class can act both as a superclass and as a descendant. Class inheritance relationships form a class hierarchy. Multiple inheritance is the definition of a class derived from several superclasses at once. Not all object-oriented programming languages ​​support multiple inheritance. Inheritance is an effective way to isolate reusable pieces of code, but it also has disadvantages, which will be discussed later.

    Abstraction. The ability to combine classes into separate groups, highlighting common characteristics that are significant for all of them (common fields and common behavior). Actually, abstraction is a consequence of inheritance: base classes do not always have their own projection onto objects of the real world, but are created solely for the purpose of highlighting the common features of an entire group of objects. For example, a furniture object is a basic concept for a table, chair and sofa, all of them are united by the fact that they are movable property, part of the interior of the premises, and they can be made for a home or office, and also refer to “economy” or “premium” ” to the class. In OOP there is a separate concept for this: an abstract class - a class whose objects are prohibited from being created, but can be used as a base class. Inheritance and abstraction make it possible to describe program data structures and relationships between them in exactly the same way as the corresponding objects in the system under consideration look like.

    An example of a class diagram constructed by abstraction during the analysis of types of existing vehicles is shown in the following figure. At the upper levels inheritance hierarchy there are abstract classes that unite vehicles according to the most significant characteristics.


    Class diagram or inheritance hierarchy "Vehicles". White squares represent abstract classes.

    Polymorphism. Another property that is a consequence of inheritance. The fact is that object-oriented programming languages ​​allow you to work with a set of objects from the same hierarchy in the same way as if they were all objects of their base class. If we return to the example about furniture, we can assume that in the context of creating an information system for a furniture store, it is reasonable to add a common “show characteristics” method to the base class for all types of furniture. When printing out the characteristics of all types of goods, the program would call this method indiscriminately for all objects, and each specific object would decide for itself what information to provide it. How this is implemented: First, the base class defines a common method for all with common behavior. In the case of our example, this will be a method that prints parameters common to all types of furniture. Secondly, in each derived class, where necessary, they redefine the base method (adding a method with the same name), where they expand the basic behavior with their own, for example, they display characteristics that are characteristic only of a specific type of furniture product. A method in a base class sometimes does not have to contain any code at all, but is needed only to define a name and a set of parameters - the signature of the method. Such methods are called abstract methods, and classes containing them automatically become abstract classes. So, polymorphism is the ability to communicate uniformly with objects of different classes through a specific interface. The ideology of polymorphism states that to communicate with an object you do not need to know its type, but rather what interface it supports.

    Interface. In some programming languages ​​(C#, Java), the concept of an interface is clearly defined - it is not only public methods and properties of the class itself. Such languages, as a rule, do not support multiple inheritance and compensate for this by allowing any object to have one base object and implement any number of interfaces. In their interpretation, an interface is like an abstract class containing only a description (signature) of public methods and properties. Implementing an interface falls on the shoulders of each class that intends to support it. The same interface can be implemented by classes of completely different hierarchies, which expands the possibilities of polymorphism. For example, the interface “saving/restoring information in a database” could be implemented by both classes of the “furniture” hierarchy and classes associated with placing orders for the manufacture of furniture, and when you click on the “save” button, the program would go through all the objects, would ask them for this interface and call the corresponding method.

Object-oriented programming is constantly evolving, giving rise to new paradigms such as aspect-oriented, subject-oriented, and even agent-oriented programming. It should be noted that the laurels of OOP haunt other theorists, and they are in a hurry to offer their own options for improving and expanding it. I wrote a separate note about this, but now I want to say a few words about prototyping programming, which implements the JavaScript client-side language. Prototypical programming eliminates the concept of a class, replacing it with a prototype - an example of an object. Thus, in a prototype-oriented language there is no concept of an object type, but there is a concept of a pattern or prototype. Prototype is an instance of an object from which other instances are created by copying (cloning) its members. In JavaScript, you do not describe the fields and methods of a class, but first create an empty object, and then add the necessary fields and methods to it (in JavaScript, a method can be defined and added to an object dynamically). In the same way, prototypes are created, which are then referred to by other objects as their prototype. If an object does not have some method or field that is specified in the call location, then it is looked for among the members of its prototype. That, I also described separately.

Some elements of modern object-oriented programming

Time does not stand still, and quite a lot of time has already passed since the advent of OOP, so it should not be surprising that today the vocabulary of object-oriented programming has grown significantly. So here are some new terms and concepts related to OOP.

    Events. A special type of objects created to notify some objects about events occurring with other objects. In different programming languages, the event mechanism is implemented in different ways: sometimes using special syntactic constructs, and sometimes using basic OOP tools.

    Universal type. The concept of generic types is not directly related to the concept of OOP, but it is the reason for the appearance of elements such as a generic class, a generic method, a generic event, etc. A generic type is a type that is parameterized by another type (set of types). What this parameter type is in the context of generic type design is unknown, although it is possible to restrict the values ​​of parameter types by forcing them to derive from a specific class or implement certain interfaces. An example is a universal class for sorting a sequence of elements, where the type of element in the sequence is unknown in advance. When designing such a class, it is important to specify that the parameter type must support the comparison operation. When creating objects of generic types, you specify a parameter explicitly, such as an integer or string type, and the object itself begins to behave as if it were an instance of a class created specifically for sorting integers or strings.

    Exceptions. Another special type of object supported by a mechanism for handling errors and exceptions built into a specific programming language. Exceptions, in addition to the error code, contain its description, possible causes and a stack of method calls that occurred before the exception occurred in the program.

Disadvantages of Object Oriented Programming

I have already said that the popularity of the object-oriented approach is enormous. I have also already noted that there are quite a lot of those who seek to expand this paradigm. But there is another way to stand out among the huge community of specialists in information technology - this is to declare that OOP has not justified itself, that it is not a panacea, but rather a placebo. Among these people there are truly very high-class specialists, such as Alexander Stepanov, Edsger Dijkstra and others, and their opinion deserves attention, but there are also those about whom they say that “something always gets in the way of a bad dancer.” Here they are, the most obvious disadvantages of OOP, which experts point out:

    OOP generates huge class hierarchies, which leads to the fact that the functionality is spread out or, as they say, blurred across the base and derived members of the class, and it becomes difficult to track the logic of the operation of a particular method.

    In some languages, all data is objects, including elementary types, and this inevitably leads to additional memory and CPU time consumption.

    Also, the speed of program execution may be adversely affected by the implementation of polymorphism, which is based on mechanisms for late binding of a method call with its specific implementation in one of the derived classes.

(as OOP stands for) is, first of all, a programming paradigm.
Programming Paradigm defines how the programmer sees the execution of the program.
Thus, the OOP paradigm is characterized by the fact that the programmer views the program as a set of interacting objects, while, for example, in functional programming the program is represented as a sequence of function calculations. Procedural programming, or, as it is also correctly called, classical operational programming, involves writing an algorithm to solve a problem; in this case, the expected properties of the final result are not described or indicated. Structured programming basically follows the same principles as procedural programming, with a few useful techniques added to it.
Non-procedural programming paradigms, which include the object-oriented paradigm, have completely different ideas.
Gradi Bucha's definition reads: “ Object-oriented programming is a programming methodology that is based on representing a program as a collection of objects, each of which is an implementation of a specific class (a special kind of type), and the classes form a hierarchy based on the principles of heritability.”
Structured and object-oriented programming are based on the scientific method known as decomposition- a method that uses the structure of the problem and allows you to break the solution of a common large problem into solving a sequence of smaller problems. Decomposition of OOP occurs not according to algorithms, but according to objects used in solving the problem. This decomposition reduces the size of software systems by reusing common mechanisms. It is known that visual programming systems or systems built on the principles of object-oriented programming are more flexible and evolve more easily over time.

History of the development of OOP originates in the late 60s. The first object-oriented language was the Simula programming language, created at a computer center in Norway. The language was intended to model real-world situations. A special feature of Simula was that the program written in the language was organized into programming objects. Objects had instructions called methods and data called variables; methods and data determined the behavior of the object. During the simulation, the object behaved according to its default behavior and, if necessary, changed the data to reflect the impact of the action assigned to it.

Today there is a sufficient number object-oriented programming languages, the most popular of which are currently C++, Delphi, Java, Visual Basic, Flash. But, in addition, many languages ​​that are usually classified as a procedural paradigm also have OOP properties, being able to work with objects. Thus, object-oriented programming in C is a large section of programming in this language, the same applies to OOP in python and many other structured languages.

When talking about OOP, another definition often comes up - visual programming. It additionally provides extensive use of object prototypes, which are defined as object classes.
Events. Many visual programming environments implement a characteristic (in addition to encapsulation, polymorphism and inheritance) of an object - an event. Events in object-oriented programming are the ability to process so-called messages (or events) received from the Windows operating system or the program itself. This principle is typical for all components of the environment that process various events that arise during program execution. Essentially, an event is some action that activates a standard reaction of an object. An event can be considered, for example, a click on a mouse button, hovering the mouse cursor over a menu item, opening a tab, etc. The order in which certain actions are performed is determined precisely by the events that occur in the system and the reaction of objects to them.
Classes and objects in OOP- various concepts. The concept of a class in OOP is a data type (the same as, for example, Real or String), and an object is a specific instance of a class (its copy), stored in computer memory as a variable of the corresponding type.
Class is a structural data type. The class includes a description of data fields, as well as procedures and functions that operate on these data fields. OOP method- these are such procedures and functions in relation to classes.
Classes have fields (like the record data type), properties that are similar to fields, but have additional descriptors that define the mechanisms for writing and reading data, and methods - subroutines that are aimed at changing the fields and properties of the class.

Basic principles of OOP

The principles of object-oriented programming, in addition to event handling, are encapsulation, inheritance, subclassing and polymorphism. They are especially useful and necessary when developing applications that are replicable and easy to maintain.
An object combines methods and properties that cannot exist separately from it. Therefore, if an object is deleted, its properties and associated methods are deleted. When copying, the same thing happens: the object is copied as a whole. OOP Encapsulation- this is the described characteristic.

OOP inheritance principle and subclasses

Absolutely all objects are created on the basis of classes, and they inherit the properties and methods of these classes. In turn, classes can be created on the basis of other classes (parents), then such classes are called subclasses (descendants). Subclasses inherit all properties and methods of the parent class. In addition, for a subclass or descendant class, you can define new, your own, properties and methods, as well as change the methods of the parent class. Changes to properties and methods of a parent class are tracked in subclasses created on the basis of this class, as well as in objects created on the basis of subclasses. This is what OOP inheritance is all about.

OOP polymorphism

In object-oriented programming, polymorphism is characterized as the interchangeability of objects with the same interface. This can be explained this way: a child class inherits instances of the methods of the parent class, but the execution of these methods can occur in a different way, corresponding to the specifics of the child class, that is, modified.
That is, if in procedural programming the name of a procedure or function uniquely identifies the executed code related to this procedure or function, then in object-oriented programming you can use the same method names to perform different actions. That is, the result of executing the same method depends on the type of object to which the method is applied.

The site presents a partial theory of object-oriented programming for beginners and OOP examples of problem solving. OOP lessons on the site are detailed algorithms for completing a given task. Based on the completion of these laboratory works, the student will be able to independently solve other similar problems in the future.
We wish you an easy and interesting learning of object-oriented programming!

Why is object-oriented programming preferred in most projects? OOP offers an effective way to deal with their complexity. Instead of viewing a program as a sequence of executable instructions, it represents it as a group of objects with certain properties and performs certain actions on them. This results in cleaner, more reliable, and more maintainable applications.

The basic principles emerged because limitations were discovered in pre-existing approaches. Among them are unlimited access to data and a large number of connections that impose restrictions on making changes. Their awareness and reasons are important in order to understand what OOP in programming is and what its benefits are.

Procedural languages

C, Pascal, FORTRAN and similar languages ​​are procedural. That is, each of their operators orders the computer to do something: receive data, add numbers, divide by six, display the result. An application in a procedural language is a list of instructions. If it is small, no other organizing principle (often called a paradigm) is required. The programmer creates a list of instructions and the computer executes them.

Division into functions

As applications get larger, the list becomes unwieldy. Few people can understand more than a few hundred instructions until they are grouped together. For this reason, the feature has become a way to make apps more understandable for their creators. In some languages, the same concept may be called a subroutine or procedure.

The application is divided into functions, each of which has a clearly defined purpose and interface.

The idea of ​​dividing procedures can be extended by grouping them into a larger object called a module, but the principle is similar: grouping components that execute lists of instructions.

The division into functions and modules is one of the cornerstones of structured programming, which was the dominant paradigm for several decades before the advent of OOP.

Structured programming problems

As applications grew larger, structured programming began to struggle. Projects were becoming too complex. Schedules shifted. More programmers were involved. The complexity grew. Costs skyrocketed, the schedule moved further, and collapse ensued.

Analysis of the reasons for these failures showed the shortcomings of the procedural paradigm. No matter how well a structured programming approach is implemented, large applications become overly complex.

What are the causes of these problems associated with procedural languages? First, functions have unlimited access to global data. Second, unrelated procedures and values ​​do not model the real world well.

When considering these issues in the context of an inventory program, one of the most important global data elements is the population of accounting units. Various functions can access them to enter a new value, display it, change it, etc.

Unlimited access

In a program written, for example, in C, there are two types of data. Local ones are hidden inside the function and are not used by other procedures.

When two or more functions need to access the same data, the latter must be global. Such, for example, is information about the items taken into account. Global data can be accessed by any procedure.

A large program has many functions and many global elements. The problem with the procedural paradigm is that it leads to even more potential connections between them.

Such a large number of connections raises several difficulties. First, it makes it difficult to understand the program structure. Secondly, it makes it difficult to make changes. A change to a global data item may require adjustments to all functions that access it.

For example, in an accounting program, someone decides that the code of the item being accounted for should not consist of 5 digits, but of 12. This will require changing from short to long. Now the code related functions must be changed to work with the new format.

When elements change in a large application, it is difficult to tell which procedures have access to them. But even if this is figured out, changing them may lead to incorrect operation of other global data. Everything is connected to everything else, so a change in one place will reverberate in another.

Real world simulation

The second and more important problem with the procedural paradigm is that its arrangement of individual data and functions does not well model things in the real world. Here we are dealing with objects such as people and cars. They don't look like data or functions. Complex real objects have attributes and behavior.

Attributes

Examples of attributes (sometimes called characteristics) for people are eye color and job title, and for cars horsepower and number of doors. As it turns out, attributes in the real world are equivalent to data in a program. They have specific meanings, such as blue (eye color) or four (number of doors).

Behavior

Behavior is what objects in the real world produce in response to some kind of influence. If you ask your boss for a salary increase, the answer will be “yes” or “no”. If you press the brake, the car will stop. Speaking and stopping are examples of behavior. A behavior is like a procedure: it is called to do something, and it does it. Thus, data and functions by themselves do not effectively model real-world objects.

Solution

An object in OOP is represented as a collection of data and functions. Only procedures, called member functions in C++, allow you to retrieve its values. The data is hidden and protected from change. Values ​​and functions are encapsulated into one whole. Encapsulation and hiding are the main terms in the description of OO languages.

If you need to change data, you know exactly which functions interact with it. No other procedures can access them. This makes it easier to write, debug, and maintain the program.

An application typically consists of multiple objects that interact with each other by calling member functions.

Today the most widely used programming) is C++ (plus-plus). Java lacks some features such as pointers, templates, and multiple inheritance, making it less powerful and versatile than C++. C# has not yet reached the popularity of C++.

It should be noted that so-called member functions in C++ are called methods in some other object-oriented languages, such as Smalltalk. Data elements are called attributes. Calling a method on an object is sending it a message.

Analogy

You can imagine objects as departments of a company. In most organizations, employees don't work in HR one day, payroll the next, and then spend a week doing retail. Each department has its own personnel with clearly assigned responsibilities. There are also their own data: salary indicators, sales, employee records, etc. People in departments work with their own information. Separating a company thus makes it easier to monitor its activities and maintain data integrity. The accounting department is responsible for If you need to know the total amount of wages paid in the southern branch in July, there is no need to rummage through the archives. It is enough to send a note to the responsible person, wait until this person gains access to the data and sends a response with the required information. This ensures compliance with regulations and the absence of outside interference. In the same way, an object in OOP provides organization for an application.

It should be remembered that object orientation does not concern the details of how the program works. Most C++ statements correspond to operators in procedural languages ​​such as C. Indeed, member functions in C++ are very similar to functions in C. Only broader context will determine whether a statement is procedural or object-oriented.

Object in OOP: Definition

When considering a programming problem in an object-oriented language, instead of asking questions about dividing it into separate functions, the problem of dividing it into objects arises. OOP thinking makes application development much easier. This occurs as a result of the similarity between software and real objects.

What things become objects in OOP? Below are typical categories.

A physical object in OOP is:

  • transport in flow models;
  • electrical elements in circuit design programs;
  • countries in the economic model;
  • aircraft in the air traffic control system.

Elements of the user's computer environment:

  • menu;
  • window;
  • graphics (line, rectangle, circle);
  • keyboard, mouse, printer, disk drives.
  • workers;
  • students;
  • clients;
  • sellers.
  • Ledger;
  • private bussiness;
  • dictionary;
  • table of latitudes and longitudes of populated areas.

The connection between real-world objects and OOP was the result of the combination of functions and data: they revolutionized programming. There is no such close correspondence in procedural languages.

Class

Objects in OOP are members of classes. What does it mean? Programming languages ​​have built-in data types. The type int, i.e. an integer, is predefined in C++. You can declare as many int variables as you like.

A set of objects of the same class is defined similarly. It defines the functions and data included in its objects without creating them, just as int does not create variables.

A class in OOP is a description of a number of similar objects. Prince, Sting and Madonna are singers. There is no one with this name, but people can be called this if they have the appropriate characteristics. An OOP object is an instance of a class.

Inheritance

In life, classes are divided into subclasses. For example, animals are divided into amphibians, mammals, birds, insects, etc.

The principle of this kind of division is that each subclass has common characteristics with the class from which it descends. All cars have wheels and an engine. These are the defining characteristics of vehicles. In addition to the general characteristics, each subclass has its own characteristics. Buses have plenty of seating and trucks have space to carry heavy loads.

Likewise, a base class can become the parent of several derived subclasses, which can be defined to share its characteristics while adding their own. Inheritance is like a function that simplifies a procedural program. If several pieces of code do almost the same thing, you can extract the common elements and put them into a single procedure. Three parts of the application can call a function to perform common actions, but they can also perform their own operations. Similarly, a base class contains data common to a group of derived classes. Like functions, inheritance shortens an object-oriented program and makes clear the relationships between its elements.

Reuse

Once a class has been created and debugged, it can be shared with other programmers for reuse in their own applications. It's like a library of functions that can be included in different applications.

In OOP, inheritance is an extension of the idea of ​​reuse. From an existing class, without changing it, you can create a new one with the addition of other functions. The ease of reusing existing software is an important advantage of OOP. This is believed to provide increased returns on the initial investment.

Creating New Data Types

Objects are useful for creating new data types. Suppose a program uses two-dimensional values ​​(for example, coordinates or latitude and longitude), and you want to express operations with them using arithmetic operations:

position1 = position + origin,

where and origin are pairs of independent numerical values. Creating a class that includes these two values ​​and declaring its variables as objects creates a new data type.

Polymorphism, overload

The = (equal) and + (plus) operators used in positional arithmetic above do not operate in the same way as with built-in types such as int. Position objects, etc. are not predefined, but rather defined programmatically. How do these operators know how to handle them? The answer is that new behavior patterns can be assigned to them. These operations will be member functions of the Position class.

The use of operators or procedures depending on what they operate on is called polymorphism. When an existing operator such as + or = is given the ability to work with a new data type, it is said to be overloaded. Overloading in OOP is a type of polymorphism. It is its important feature.

The book about OOP “Object-Oriented Programming for Dummies” will allow everyone to familiarize themselves with this topic in more detail.

general information

OOP is a programming style that appeared in the 80s of the 20th century. Unlike procedural languages, where data and instructions for processing it exist separately, in object-oriented programming this information is combined into a single entity.

Basic principles of OOP

Inheritance

The second principle of OOP, inheritance, is the ability of one class to use the methods of another without repeating their actual implementation. Inheritance allows you to get rid of redundancy in source code.

Polymorphism

Another principle of OOP is polymorphism. Its use means that for manipulating objects of varying degrees of complexity, you can create one interface that will react differently to events and at the same time correctly implement the assigned tasks.

OOP languages

OOP principles are used in the most popular programming languages ​​such as C++ and Java, in which a significant part of programs and applications are developed. There are also less used OOP languages ​​- Delphi, Object Pascal, Ruby and many others.

Criticism of OOP

Despite the mostly positive statements towards this methodology, the principles of OOP are often criticized. Like OOP, it has its drawbacks.

Firstly, the difficulty of the transition. It will take quite a lot of time to understand the principles of OOP, especially for people who work closely only with procedural programming languages.

Secondly, the disadvantage is more complex documentation, since it will be necessary not only to describe classes and objects, but also specific cases of their implementation.

Thirdly, excessive universality of methods can lead to the fact that the source code and developed programs will be overloaded with functions and capabilities that are not in demand in this particular case. In addition, they note inefficiency in terms of memory allocation. However, regardless of the opinions of others, the number of OOP programmers is constantly growing, and the languages ​​themselves are developing rapidly.

By the will of fate, I have to read a special course on design patterns at a university. The special course is compulsory, therefore, the students who come to me are very different. Of course, there are also practicing programmers among them. But, unfortunately, most people have difficulty even understanding the basic terms of OOP.

To do this, I tried to explain the basic concepts of OOP (class, object, interface, abstraction, encapsulation, inheritance and polymorphism) using more or less live examples.

The first part below is about classes, objects and interfaces.
The second part illustrates encapsulation, polymorphism and inheritance

Basic concepts of OOP

Class
Imagine that you are designing a car. You know that a car must contain an engine, suspension, two headlights, 4 wheels, etc. You also know that your car must be able to accelerate and slow down, make turns and go in reverse. And, most importantly, you know exactly how the engine and wheels interact, according to what laws the camshaft and crankshaft move, as well as how the differentials are designed. You are confident in your knowledge and start designing.

You describe all the parts that make up your car, as well as how these parts interact with each other. In addition, you describe what the user must do to make the car brake or turn on the high beam headlights. The result of your work will be a sketch. You have just developed what is called in OOP Class.

Class is a way of describing an entity that defines a state and behavior that depends on this state, as well as rules for interacting with this entity (contract).

From a programming point of view, a class can be considered as a set of data (fields, attributes, class members) and functions for working with them (methods).

From the point of view of program structure, a class is a complex data type.

In our case, the class will display an entity - a car. The class attributes will be the engine, suspension, body, four wheels, etc. Class methods will be “open the door”, “press the gas pedal”, and also “pump a portion of gasoline from the gas tank into the engine”. The first two methods are available for execution by other classes (in particular, the “Driver” class). The latter describes interactions within the class and is not accessible to the user.

From now on, although the word “user” is associated with Solitaire and Microsoft Word, we will refer to the programmers who use your class as users, including yourself. We will call the person who is the author of the class the developer.

An object
You did a great job and the machines developed according to your drawings are rolling off the assembly line. Here they are, standing in neat rows in the factory yard. Each of them exactly repeats your drawings. All systems interact exactly as you designed. But every car is unique. They all have body and engine numbers, but these numbers are all different, the cars differ in color, and some even have castings instead of stamped wheels. These cars are essentially objects of your class.

Object (instance) is an individual representative of a class that has a specific state and behavior that is entirely determined by the class.

In simple terms, an object has specific attribute values ​​and methods that operate on those values ​​based on rules defined in the class. In this example, if the class is some abstract car from the “world of ideas,” then the object is a concrete car standing under your windows.

Interface
When we walk up to a coffee machine or get behind the wheel, we begin an interaction with them. Usually, interaction occurs using a certain set of elements: a slot for accepting coins, a button for selecting a drink and a compartment for dispensing a glass in a coffee machine; steering wheel, pedals, gear shift lever in a car. There is always some limited set of controls with which we can interact.

Interface is a set of class methods that are available for use by other classes.

Obviously, the interface of a class will be the set of all its public methods together with a set of public attributes. Essentially, an interface specifies a class, clearly defining all possible actions on it.
A good example of an interface is the dashboard of a car, which allows you to call up methods such as speeding up, braking, turning, changing gears, turning on headlights, etc. That is, all the actions that another class (in our case, the driver) can perform when interacting with the car.

When describing a class interface, it is very important to strike a balance between flexibility and simplicity. A class with a simple interface will be easy to use, but there will be problems that it cannot solve. At the same time, if the interface is flexible, then most likely it will consist of quite complex methods with a large number of parameters that will allow you to do a lot, but using it will be fraught with great difficulties and the risk of making a mistake, something mixed up

An example of a simple interface would be a car with an automatic transmission. Any blonde who has completed a two-week driving course will be able to master its operation very quickly. On the other hand, to master the control of a modern passenger aircraft, you need several months, or even years of hard training. I wouldn't want to be on board a Boeing piloted by someone who has two weeks of flying experience. On the other hand, you will never get a car to take off and fly from Moscow to Washington.