Fundamentals of object-oriented programming. What is OOP with examples

Abstract Data Types

The concept of abstract data types is key in programming. Abstraction implies separation and independent consideration of the interface and implementation.

Let's look at an example. We all watch television programs. Let's call the TV a module or object. This object has an interface with the user, i.e. controls (a set of buttons), image and sound reproduction. The more advanced the interface, the more convenient the TV is to use. We switch programs by pressing certain buttons, and at the same time we do not think about the physical processes occurring in the TV. Experts know about this. When we choose a TV, we are interested in its price and performance parameters, i.e. quality of image, sound, etc. However, we are not interested in what is inside. In other words, we return to the properties of the object (module), which are the interface and implementation. The main purpose of abstraction in programming is precisely to separate the interface from the implementation.

Let's return to our example. Suppose some subject is confident that he knows the structure of the TV well. He removes the lid and begins to “improve” it. Although sometimes this leads to some intermediate (local) successes, the final result is almost always negative. Therefore, such actions must be prohibited. In programming, this is supported by mechanisms for denying access or hiding internal components. Each object (module) is given the right to manage “its own property”, i.e. these functions and operations. Ignoring this principle violates the stability of the system and often leads to its complete destruction. The principle of abstraction requires the use of hiding mechanisms that prevent intentional or accidental modification of internal components.

Data abstraction involves defining and considering abstract data types(ATD) or, what is the same, new types of data entered by the user.

Abstract data type is a collection of data along with many operations that can be performed on this data.

Concept of object-oriented programming

According to the definition of an authority in the field of object-oriented methods of program development, Gradi Bucha, “object-oriented programming (OOP) is a programming methodology that is based on representing a program as a collection of objects, each of which is an implementation of a certain class (a special kind of type), and classes form a hierarchy on the principles of heritability.”

Object-oriented methodology, like the structural methodology, was created with the goal of disciplining the development process of large software systems and thereby reducing their complexity and cost.

An object-oriented methodology has the same goals as a structural methodology, but addresses them from a different starting point and, in most cases, allows you to manage more complex projects than a structural methodology.

As you know, one of the principles of project complexity management is decomposition. Gradi Booch distinguishes two types of decomposition: algorithmic (as he calls decomposition supported by structural methods) and object-oriented, the difference between which, in his opinion, is as follows: “The division by algorithms concentrates attention on the order of events occurring, and the division by objects gives special importance to the factors either causing actions or being the objects of application of these actions.”

In other words, algorithmic decomposition takes more into account the structure of relationships between parts of a complex problem, while object-oriented decomposition pays more attention to the nature of the relationships.

In practice, it is recommended to use both types of decomposition: when creating large projects, it is advisable to first use an object-oriented approach to create a general hierarchy of objects that reflect the essence of the programmable task, and then use algorithmic decomposition into modules to simplify the development and maintenance of the software package.

OO programming is undoubtedly one of the most interesting areas for professional software development.

Objects and classes

The basic blocks of an object-oriented program are objects and classes. In terms of content, an object can be represented as something felt or imagined and having well-defined behavior. Thus, an object can either be seen, touched, or at least known to be there, for example represented as information stored in computer memory. Let us define an object, adhering to the opinion of Gradi Bucha: “An object is a tangible entity that clearly manifests its behavior.”

An object - it is part of the reality around us, i.e. it exists in time and space (the concept of an object in programming was first introduced in the Simula language). Formally, the object is quite difficult to define. This can be done through some properties, namely: the object has state, behavior and can be uniquely identified (in other words, has a unique name).

Class - it is a set of objects that have a common structure and common behavior. A class is a description (abstraction) that shows how to construct a variable of this class that exists in time and space, called object. The meaning of the sentences “description of class variables” and “description of class objects” is the same.

An object has a condition, behavior and a passport (a means for its unambiguous identification); the structure and behavior of objects are described in classes, of which they are variables.

Let us now define the concepts state, behavior and identification object.

Object state combines all of its data fields (static component, i.e. unchanging) and the current values ​​of each of these fields (dynamic component, i.e. usually changing).

Behavior expresses the dynamics of changes in the states of an object and its reaction to incoming messages, i.e. how an object changes its states and interacts with other objects.

Identification(recognition) of an object is a property that allows you to distinguish an object from other objects of the same or other classes. Identification is carried out through a unique name (passport), which is assigned to an object in the program, just like any other variable.

It was already said above that the procedural (as well as modular) approach allows you to build programs consisting of a set of procedures (subroutines) that implement given algorithms. On the other hand, the object-oriented approach represents programs as a set of objects that interact with each other. Objects interact through messages. Let's assume our object is a circle. Then the message sent to this object could be: "draw yourself." When we say that a message is sent to an object, we are actually calling some function this object (function component). So, in the above example, we will call a function that will draw a circle on the display screen.

Basic principles of OOP

The basic principles of the object-oriented programming style include:

  • packaging or encapsulation;
  • inheritance;
  • polymorphism;
  • message transmission.

Packaging (encapsulation)

involves combining data and functions that manipulate this data in one object. Access to some data within the package may be either denied or restricted.

An object is characterized as a set of all its properties (for example, for animals - the presence of a head, ears, eyes, etc.) and their current values ​​(head - large, ears - long, eyes - yellow, etc.), so and the set of actions acceptable for this object (the ability to eat, sit, stand, run, etc.). This combination in a single object of both “material” component parts (head, ears, tail, paws) and actions that manipulate these parts (the “run” action quickly moves the paws) is called encapsulation.

In OOP, data are called object fields, and algorithms are called object methods.

Encapsulation allows you to isolate an object from its external environment to the maximum extent possible. It significantly increases the reliability of developed programs, because Algorithms localized in an object exchange relatively small amounts of data with the program, and the amount and type of this data is usually carefully controlled. As a result, replacing or modifying algorithms and data encapsulated in an object, as a rule, does not entail poorly traceable consequences for the program as a whole. Another important consequence of encapsulation is the ease of exchanging objects, transferring them from one program to another.

Inheritance

Both structural and object-oriented methodologies have the goal of constructing a hierarchical tree of relationships between objects (subtasks). But if the structural hierarchy is built on the simple principle of dividing the whole into its component parts,

then when creating an object-oriented hierarchy, a different view of the same original object is taken. An object-oriented hierarchy necessarily reflects the inheritance of properties of parent (overlying) object types to child (underlying) object types.

According to Gradi Booch, “inheritance is a relationship between objects in which one object repeats the structure and behavior of another.”

The principle of inheritance operates in life everywhere and every day. Mammals and birds inherit the characteristics of living organisms; unlike plants, the eagle and raven inherit a common property for birds - the ability to fly. On the other hand, lions, tigers, leopards inherit the “structure” and behavior characteristic of representatives of the order Felidae, etc.

Types at the top levels of an object-oriented hierarchy generally do not have concrete instances of objects. There is, for example, no specific living organism that is itself called a “mammal” or a “bird.” Such types are called abstract. Specific instances of objects, as a rule, have types of the lowest levels of the OO hierarchy: “Gena the crocodile” is a specific instance of an object of the “crocodile” type, “Matroskin the cat” is a specific instance of an object of the “cat” type.

Inheritance allows you to use class libraries and develop them (improve and modify library classes) in a specific program. Inheritance allows you to create new objects by changing or adding properties to existing ones. The inheritor object receives all the fields and methods of the ancestor, but can add its own fields, add its own methods, or override inherited methods of the same name with its own methods.

The principle of inheritance solves the problem of modifying the properties of an object and gives OOP as a whole exceptional flexibility. When working with objects, a programmer usually selects an object that is closest in its properties to solving a specific problem, and creates one or more descendants from it that “can” do what is not implemented in the parent.

Consistent implementation of the “inherit and change” principle fits well with and greatly encourages an incremental approach to the development of large software projects.

When you build a new class by inheriting from an existing class, you can:

  • add new data components to the new class;
  • add new function components to the new class;
  • replace in the new class the function components inherited from the old class.

Polymorphism

allows you to use the same functions to solve different problems. Polymorphism is expressed in the fact that under one name various actions are hidden, the content of which depends on the type of object.

Polymorphism is the property of related objects (that is, objects that have one common parent) to solve problems of similar meaning in different ways. For example, the action of “running” is common to most animals. However, each of them (lion, elephant, crocodile, turtle) performs this action in a different way.

With a traditional (non-object-oriented) approach to programming, the programmer will move the animals by calling a separate subroutine for a specific animal and a specific action.

Within the framework of OOP, the behavioral properties of an object are determined by the set of methods included in it, the programmer only indicates which object needs to perform which of its inherent actions, and (for the example under consideration) once described animal objects will move themselves in a way characteristic of them, using the included in its composition methods. By changing the algorithm of a particular method in the descendants of an object, the programmer can give these descendants specific properties that the parent does not have. To change a method, you need to override it in a child, i.e. declare a method of the same name in the descendant and implement the necessary actions in it. As a result, two methods of the same name will operate in the parent object and the child object, having a different algorithmic basis and, therefore, giving the objects different properties. This is called object polymorphism.

Thus, in our example with animal objects, the action “run” will be called a polymorphic action, and the variety of forms of manifestation of this action will be called polymorphism.

Description of the object type

A class or object is a data structure that contains fields and methods. Like any data structure, it begins with a reserved word and ends with the operator end. The formal syntax is not complicated: a description of an object type is obtained by replacing the word in the record description record on word object or class and add declaration of functions and procedures above the fields.

Type<имя типа объекта>= object
<поле>;
<поле>;
….
<метод>;
<метод>;
end ;

There is a special reserved word in ObjectPascal class for describing objects, borrowed from C++.

Type<имя типа объекта>= class
<поле>;
….
<метод>;
<метод>;
end ;

ObjectPascal supports both models of object description.

An object component is either a field or a method. The field contains the name and data type. A method is a procedure or function declared inside an object type declaration, including special procedures that create and destroy objects (constructors and destructors). A method declaration within an object type declaration consists only of a header. This is a type of preliminary description of a subroutine. The body of the method follows the object type declaration.

Example. An object type "ancestor" is introduced, which has a Name data field and can perform two actions:

  • proclaim: “I am an ancestor!”;
  • give your name.

Type tPredoc = object Name: string ; (object data field)
Procedure Declaration ; (declaration of object methods)
Procedure MyName ;
End ;

The texts of subroutines that implement object methods must be given in the section describing procedures and functions. The headers when describing the method implementation repeat the headers given in the type description, but are supplemented by the object name, which is separated from the procedure name by a dot. In our example:

Procedure tPredoc.Declaration ; (object method implementation)
begin
writeln("I am an ancestor!");
end ;
Procedure tPredoc.MyName ; (object method implementation)
begin
writeln("I am", Name);
end;

Inside the method descriptions for fields and methods of this type referred to simply by name. So the MyName method uses the Name field without explicitly indicating its ownership of the object, as if the implicit with statement were executed<переменная_типа_объект>do.

Objects also mean variables of an object type - they are called copies. Like any variable, an instance has a name and a type: they must be declared.

…….(declaration of an object type and description of its methods)
var v 1: tPredoc ; (object instance declaration)
begin
v1. Name:= "Petrov Nikolai Ivanovich";
v1.Declaration;
v1.MyName
end.

Using a v1 object's data field is the same syntax as using record fields. Calling methods of an object instance means that the specified method is called with the data of the object v 1. As a result, the lines will be displayed on the screen

I am an ancestor!
I am Nikolai Ivanovich Petrov

Similar to records, fields of object type variables can be accessed using either qualified identifiers or a with statement.

For example, in the text of the program, instead of operators

it is possible to use a with operator of this type

with v1 do
begin
Name:= "Petrov Nikolai Ivanovich";
Declaration ;
MyName
End ;

Moreover, using the with statement with object types, as well as for records, is not only possible, but also recommended.

Type hierarchy (inheritance)

Types can be arranged in a hierarchy. An object can inherit components from another object type. An inheritor object is a child. The object that is inherited is the ancestor. We emphasize that inheritance only applies to types, not to instances of objects.

If an object type (ancestor, parent) is introduced, and it needs to be supplemented with fields or methods, then a new type is introduced, declared a successor (descendant, child type) of the first one, and only new fields and methods are described. The descendant contains all the fields of the ancestor type. Note that the fields and methods of the ancestor are available to the child without special instructions. If the descendant description repeats the names of the ancestor's fields or methods, then the new descriptions override the ancestor's fields and methods.

OOP always starts with a base class. This is the template for the base object. The next step is to define a new class, which is called a derived class and is an extension of the base one.

A derived class can include additional methods that do not exist in the base class. It can redefine methods (or even remove them entirely).

A derived class should not override all methods of the base class. Each new object inherits the properties of the base class; you only need to define those methods that are new or have been changed. All other methods of the base class are considered part of the derived class. This is convenient because... when a method is changed in the base class, it is automatically changed in all derived classes.

The inheritance process can continue. A class that is derived from a base class can itself become a base class for other derived classes. In this way, OO programs create a class hierarchy.

Most often, the structure of a class hierarchy is described as a tree. The tops of the tree correspond to classes, and the root corresponds to a class that describes something common (most common) to all other classes.

Inheritance by child types of information fields and methods of their parent types is carried out according to the following rules.

Rule 1. Information fields and methods of a parent type are inherited by all its child types, regardless of the number of intermediate levels of the hierarchy.

Rule 2. Access to fields and methods of parent types within the definition of any child types is performed as if they were described in the child type itself.

Rule 3. No child type can use the field identifiers of its parent types.

Rule 4. A child type can define an arbitrary number of its own methods and information fields.

Rule 5. Any change to the text in a parent method automatically affects all methods of the child types that call it.

Rule 6. In contrast to information fields, method identifiers in child types can be the same as method names in parent types. In this case, the child method is said to override (suppress) the parent method of the same name. Within a child type, when specifying the name of such a method, the child method will be called, and not the parent.

Let's continue with our example. In addition to the tPredoc ancestor type we introduced, we can introduce descendant types:

ture tSon= object(tPredoc) (Type that inherits tPredoc)
procedure Declaration; (overlapping ancestor methods)
procedure My Name(Predoc: tPredoc);
end ;

Type tGrandSon=object(tSon) (Type inheriting from tSon)
procedure Declaration ; (overlapping ancestor methods)
end ;

The name of the ancestor type is given in parentheses after the word object. We have created a hereditary hierarchy of three types: tSon (“son”) is the heir to the tPredoc type, and the tGrandSon (“grandson”) type is the heir to the tSon type. The tSon type overrides the Declaration and My N a m e methods, but inherits the Name field. The tGrandSon type overrides only the Declaration method and inherits the Name field from its common ancestor, and the overridden Declaration method from its immediate ancestor (type tSon).

Let's figure out what exactly we want to change in the parent methods. The fact is that the “son” must proclaim somewhat differently than his ancestor, namely, say “I am the father!”

procedure tSon.Declaration ; (implementation of methods of descendant objects)
begin
writeln("I am the father!");
end;

And when giving his name, the “son” must provide the following information:

  • I<фамилия имя отчество >
  • I am the son<фамилия имя отчество своего предка>

procedure tSon .My Name (predoc: tPredoc);
begin
inherited Mu Name; (call immediate ancestor method)
writeln("I am the son", predoc.Name, "a");
end;

In our example, the descendant tSon from the My Name method calls the method of the same name on its immediate ancestor type tPredoc. This call is provided by the directive inherited, followed by the immediate ancestor method being called. If there is a need to call a method of a distant ancestor in some child type at any level of the hierarchy, then this can be done using a qualified identifier, i.e. indicate explicitly the type name of the parent object and, separated by a dot, the name of its method:

Now let's deal with the "grandson". The method in which the "grandson" says its name is exactly the same as its immediate ancestor (type tSon), so there is no need to override this method, it is better to automatically inherit this method and use it as your own. But in the Declaration method you need to declare “I am a grandson!”, so the method will have to be redefined.

procedure tGrandSon.Declaration;
begin
writeln("I am a grandson!");
end;

Let's consider an example of a program in which we define an instance of the tPredoc type, call it “grandfather”, an instance of the tSon type “father”, and an instance of the tGrandSon type “grandson”. Let's ask them to introduce themselves.

Example program using OOP

(program title)
……………….
(section of descriptions of types, including object types tPredoc, tSon, tGrandSon)
(Note! Instances of object types can be described as typed constants, which is what we have done below for the example)
const ded: tPredoc = (Name: "Nikolai Ivanovich Petrov");
otec: tSon = (Name: "Petrov Sergey Nikolaevich");
vnuk: tGrandSon = (Name: "Petrov Oleg Sergeevich");
(section of descriptions of procedures and functions, where all methods declared in object types must be written)
begin
ded.Declaration; (calling common ancestor methods)
ded.My Name;
writeln;
otec.Declaration;
otec.MyName(ded); (calling methods of an otec object of type tSon)
writeln;
vnuk.Declaration; (calling methods of a vnuk object of type tGrandSon)
vnuk.MyName(otec);
end.

Our program will display:

An example of displaying the result

I am an ancestor!
I am Nikolai Ivanovich Petrov

I am the father!
I am Petrov Sergey Nikolaevich
I am the son of Petrov Nikolai Ivanovich

I am a grandson!
I am Petrov Oleg Sergeevich
I am the son of Sergei Nikolaevich Petrov

Please note that in the procedure header tSon. MyName is given a tPredoc data type as a parameter, and when using this procedure, variables of both tPredoc and tSon types are passed to it. This is possible because the ancestor is type compatible with its descendants. The opposite is not true. If we replace tSon in the procedure header. MyName when describing parameters of type tPredoc on tSon , the compiler will indicate type incompatibility when using the ded variable in the otec line. MyName(ded).

Polymorphism and virtual methods

Polymorphism– this is the property of related objects (i.e. objects that have the same parent) to solve problems of similar meaning in different ways.

Two or more classes that are derived from the same base class are called polymorphic. This means that they can have common characteristics, but also have their own properties.

Within OOP, the behavioral properties of an object are determined by the set of methods included in it. By changing the algorithm of a particular method in the descendants of an object, the programmer can give these descendants specific properties that the parent does not have. To change a method, you need to override it in a child, i.e. declare a method of the same name in the descendant and implement the necessary actions in it. As a result, two methods of the same name will operate in the parent object and the child object, having a different algorithmic basis and, therefore, giving the objects different properties. This is called object polymorphism.

In the example discussed above, all three object types tPredoc, tSon and tGrandSon have the same methods Declaration and MyName. But the tSon object type implements the MyName method slightly differently than its ancestor. And all three Declaration methods of the same name are executed differently for each object.

Object methods are static, virtual and dynamic.

Static methods

included in the program code during compilation. This means that before using the program it is determined which procedure will be called at a given point. The compiler determines what type of object is being used in a given call and substitutes a method for that object.

Objects of different types can have static methods of the same name. In this case, the required method is determined by the type of the object instance.

This is convenient, since methods of different types of objects that have the same meaning can be named the same, and this simplifies the understanding of both tasks and programs. Static overlap is the first step of polymorphism. Identical names are a matter of programming convenience, not a principle.

Virtual methods

unlike static ones, they are connected to the main code at the stage of program execution. Virtual methods provide the ability to determine the type and instantiate an instance of an object at runtime, and then call methods on that object.

This fundamentally new mechanism, called late binding, provides polymorphism, i.e. a different way of behavior for different, but homogeneous (in the sense of inheritance) objects.

The description of a virtual method differs from the description of a regular method by adding a function word after the method header virtual .

procedure Method (parameter list); virtual;

The use of virtual methods in the object type hierarchy has certain limitations:

  • if a method is declared as virtual, then it cannot be overridden in a descendant type static method;
  • objects that have virtual methods are initialized by special procedures, which, in essence, are also virtual and are called constructor ;
  • lists of variables and function types in the headers of overlapping virtual procedures and functions must match completely;

Usually on constructor the work of initializing an object instance is assigned: assigning initial values ​​to fields, initial display on the screen, etc.

In addition to the actions put into it by the programmer, the constructor prepares a mechanism for late binding of virtual methods. This means that before any virtual method is called, some constructor must be executed.

A constructor is a special method that initializes an object containing virtual methods. The constructor header looks like this:

constructor Method(parameter list);

Reserved word constructor replaces the words procedure and virtual .

The main and special purpose of the constructor is to establish connections with the virtual method table (VMT) - a structure containing references to virtual methods. Thus, the constructor initializes the object by establishing a connection between the object and the VMT with the addresses of the virtual method codes. Late binding occurs during initialization.

Each object has its own VMT virtual method table. This is what allows the method of the same name to call different procedures.

Having mentioned the constructor, we should also say about destructor. Its role is the opposite: perform actions that complete work with the object, close all files, clear dynamic memory, clear the screen, etc.

The destructor header looks like this:

destructor Done ;

The main purpose of destructors is to destroy the VMT of a given object. Often the destructor does nothing else and is an empty procedure.

destructor Done ;
begin end ;

It is based on representing a program as a set of objects. Each object belongs to a class, which, in turn, takes its place in the inherited hierarchy. Using OOP minimizes redundant data, which improves controllability and understanding of the program.

What is OOP

It arose as a result of the development of procedural programming. The basis of object-oriented languages ​​are the following principles:

  • encapsulation;
  • inheritance;
  • polymorphism.

Some principles that were originally laid down in the first OYA have undergone significant changes.

Examples of object-oriented languages:

  1. Pascal. With the release of Delphi 7, it officially became known as Delphi. The main area of ​​use of Object Pascal is writing application software.
  2. C++ is widely used for development software, is one of the most popular languages. Used to create OS, application programs, device drivers, applications, servers, games.
  3. Java - translated into bytecode, processed by the Java virtual machine. The advantage of this method of execution is its independence from the operating system and hardware. Existing families: Standard Edition, Enterprise Edition, Micro Edition, Card.
  4. JavaScript is used as a scripting language for web pages. The syntax is very similar to C and Java. Is an implementation of Ecmascript. Ecmascript itself is used as a basis for building others such as JScript, ActionScript.
  5. Objective-C is built on the C language, and the C code itself is understandable by the Objective-C compiler.
  6. Perl is a high-level, interpreted, dynamic, general-purpose language. It has rich capabilities for working with text and was originally designed specifically for text manipulation. Now used in systems administration, development, network programming, bioinformatics, etc.
  7. PHP. The abbreviation translates as hypertext preprocessor. Used for developing web applications, in particular the server part. With its help, you can create gui applications using WinBinder packages.
  8. Python is a general-purpose language focused on improving developer productivity and code readability. The Cython project was developed, with the help of which programs written in Python are translated into code in the C language.

Abstraction

Any book like “Object-Oriented Programming for Dummies” highlights one of the main principles - abstraction. The idea is to separate the details or characteristics of a program implementation into those that are important and those that are not. Necessary for large projects, it allows you to work at different levels of system representation without specifying details.

An abstract data type is represented as an interface or structure. Allows you not to think about the level of implementation detail. ADT is independent of other code sections.

David Wheeler's famous aphorism states: All problems in computer science can be solved at another level of abstraction.

Inheritance

Object-oriented languages ​​are inheritable - this is one of the most important principles.

Indicates that some type of functionality can be reused. A class that inherits the properties of another is called a derived, descendant, or subclass. The one from which inheritance occurs is called the ancestor, base or superclass. The descendant-heir relationship gives rise to a special hierarchy.

There are several types of inheritance:

  • simple;
  • plural.

With multiple inheritance, there can be several children from one ancestor, while with simple inheritance there can be only one. This is the main difference between the types.

Inheritance looks like this:

function draw() (

return "just animal";

function eat() (

return "the animal is eating";

class Cow extends Animal (

function draw() (

Return "something that looks like a cow";

We see that class Cow inherited all methods from class Animal. Now, if we execute Cow.eat(), we get "the animal is eating", so the draw() method is changed. Cow.draw() will return “something that looks like a cow”, and Animal.draw() will return “just animal”.

Encapsulation

Encapsulation limits the access of components to others, associates data with methods for processing. The private access specifier is used for encapsulation.

Usually the concepts of encapsulation and hiding are identical, but some languages ​​differentiate these concepts. In other words, performance-critical properties are protected and cannot be changed.

function __construct($name) (

$this->name = $name;

function getName() (

return $this->name;

Name is accepted as constructor arguments. When the constructor is used in other parts of the code, nothing will be able to change the name element. As you can see, it is indicated internally; it is not available for other parts of the code.

Polymorphism

Polymorphism allows you to use the same name to solve similar, but technically different problems.

The example above contains a table. We see class CardDesk and class GraphicalObject. Both have a function called draw(). It performs different actions, although it has the same name.

Ad hoc polymorphism or special polymorphism uses:

  • overloading functions and methods;
  • cast.

Overloading involves the use of several functions with the same name, when the selection of suitable ones occurs at the compilation stage.

Type casting means converting a value of one type to a value of another type. There is an explicit conversion - a function is applied that takes one type and returns another, implicit - is performed by the compiler or interpreter.

“One interface, many implementations” Bjarne Stroustrup.

Class

A class is a data type that consists of a single set of fields and methods.

Has internal and external interfaces for content management. When copying via assignment, the interface is copied, but not the data. Different species interact with each other through:

  • inheritance;
  • associations;
  • aggregation.

When inheriting, a child class inherits all the properties of the parent; association implies the interaction of objects. When an object of one class is included in another, it is called aggregation. But when they still depend on each other in terms of their lifetime, this is composition.

One of the main characteristics is the scope. The concept is defined differently by different languages.

In Object Pascal it is described as follows:

ClassName = class(SuperClass)

(use of elements is limited only within the module)

(fields are indicated here)

(access specifier became available with Delphi 2007, meaning the same as private)

(elements can be used inside ClassName or when inheriting)

(elements are available to everyone, they are displayed in the Object Inspector)

Here SuperClass is the ancestor from which inheritance occurs.

For C++ the creation looks like this:

class MyClass: public Parent

MyClass(); // constructor

~MyClass(); // destructor

In this example, Parent is the ancestor, if any. The specifiers private, public, protected mean the same thing as in the previous example in Pascal. We also see a constructor and destructor available for any part of the program. In C++, all elements are private by default, so this can be omitted.

Implementation Features

At the center of object-oriented languages ​​is the object, it is part of the class. It consists of:

  • fields;
  • method.

The data field describes the parameters of the object. They represent a certain value that belongs to a class and describe its state and properties. They are closed by default, and data changes occur through the use of various methods.

A method is a set of functions that define all possible actions that can be performed on an object. All objects interact by calling each other's methods. They can be external or internal, which is specified by access modifiers.

OOP methodologies

The following methodologies exist:

  • Component-oriented programming;
  • Prototype programming;
  • Class-oriented programming.

Component-oriented programming is based on the concept of a component - a component of a program that is intended to be reused. It is implemented as a set of structures with a common feature, rules, and restrictions. The approach is used in the object-oriented Java language, where component orientation is implemented through “JavaBeans” written according to the same rules.

In prototypic programming there is no concept of a class - inheritance is achieved by cloning an existing prototype. This is the basis of object-oriented javascript languages and other ecmascript dialects, as well as lua or lo. Main features:

  • descendants should not retain structural similarity to the prototype (in the class-instance relationship this is exactly what happens);
  • when copying a prototype, all methods are inherited one to one.

Class-oriented programming focuses on and instance. A class defines a common structure, behavior for the instances that adopt it.

Object-oriented languages

All OOPs fully comply with OOP principles - elements are objects that have properties. In this case, there may be additional funds.

OOYA necessarily contains a set of the following elements:

  • declaration of classes with fields, methods;
  • extension through inheritance of functions;
  • polymorphic behavior.

In addition to the above list, additional tools may be added:

  • constructor, destructor, finalizers;
  • properties;
  • indexers;
  • access modifiers.

Some OYA meet all the basic elements, others partially. Still others are hybrid, that is, they are combined with subsystems of other paradigms. Generally, OOP principles can be applied to a non-object-oriented language too. However, the use of OTL does not yet make the code object-oriented.

Language languages ​​support more than one paradigm. For example, PHP or JavaScript support functional, procedural, object-oriented programming. Java works with five paradigms: object-oriented, generic, procedural, aspect-oriented, concurrent. C# is considered one of the most successful examples of multi-paradigmism. It supports the same approaches as Java, with the addition of a reflective paradigm added to the list. A language like Oz is designed to bring together all the concepts traditionally associated with different software paradigms.

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 operating system), as well as a number of procedures for working with a 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 additional characteristic class members, determining whether they can be accessed by 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 and so on.)

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 effective method highlighting reusable code fragments, but it also has disadvantages, which will be discussed below.

    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 information system For a furniture store, it would be 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 such elements as the generic class, universal method, universal 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 we improve computer technology computers began to be used to solve more and more complex problems. It turned out that to solve complex problems, not only the increased computing power of computers is important, but also the efficiency of writing complex programs. Object-oriented programming(OOP) appeared precisely as an effective way to overcome the difficulties that arise when creating complex programs.

The most significant part of OOP is a special approach to solving complex programming problems called object-oriented analysis, and object-oriented programming languages ​​are simply convenient tools for implementing this approach.

Story

The founders of OOP are the outstanding Norwegian scientists Cristen Nygaard and Ole-Johan Dahl. While working on navigation simulations, Nygaard realized that existing software tools were ineffective in creating such complex programs, and then Nygaard began to develop concepts for new programming that would overcome the barriers of complexity, which was later called object-oriented(the term itself was coined by Alan Kay, the author of the Java language). Together with Ole-Johan Dahl, Nygaard developed the basic principles of OOP and the practical mechanisms for their implementation, which were then embodied in the first OOP Simula. The merits of these scientists were appreciated by the world scientific community, and in 2001 Nygaard and Dahl became laureates of the Alan Turing Award - a kind of analogue of the Nobel Prize in the field of computer science.

The Simula language was famous in academic circles, but for a number of reasons it did not gain popularity among commercial software developers. Nevertheless, the basic ideas and capabilities of OOP were very attractive to programmers. Subsequently, other OYs were created: SmallTalk (1980), C++ (1985), Eiffel (1986), Object Pascal (1986) and Delphi (1995), Oberon-2 (1991), Java (1991), Visual Basic (1991) and a lot others. Some of these languages ​​have become industry standards in programming.

Features of OOP

The main idea of ​​OOP is that one should create software structures whose behavior and interaction imitate the behavior and interaction of real-world objects (i.e., virtual analogues of real entities are created in the program). Object-oriented programming languages ​​should provide the means to implement this approach quickly and easily.

In everyday life, people use (even unconsciously) various techniques of “economy of thinking” that allow them to comprehend and express complex phenomena in simple concepts. Typical “economy of thinking” techniques are:

· abstraction (discarding unimportant details);

· generalization (identification of common essential features of different phenomena or objects);

· classification (awareness of the connection between phenomena and the degree of their similarity).

These simple techniques help a person cope with the complexity of the phenomena under consideration. And object-oriented programming languages ​​should also provide similar means to “combat the complexity” of programs. To implement the object-oriented approach, new concepts are introduced into programming languages:

· objects - special program structures that combine data and algorithms for processing them;

· encapsulation - hiding the details of the functioning of objects;

· inheritance is a “shortcut” way to create new classes;

· polymorphism - the ability to use several implementations of one function.

Objects and classes

Objects are special software units consisting of data and algorithms to process exactly this data. The data included in an object is called fields(attributes, properties, members). The algorithms included in the object are called methods(services, operations, member functions). Unfortunately, there is no single established terminology in OOP, and different languages ​​use different terms to denote the same concepts.

Classes- These are object data types. Just as integers belong to an integer type (such as integer or byte), objects also belong to an object type called a class. All objects of the same class have the same set of fields and the same set of methods.

In some languages ​​(C++, Java) objects are called instances of the class(instances).

The usefulness of using classes and objects is that checking the logical (semantic) correspondence between data and functions for processing data becomes a trivial task and can be largely delegated to the compiler (computer) - now it can itself determine the incorrect use of data.

Encapsulation

Encapsulation (literally “hiding”) is the controlled hiding of information about the internal structure of a class. A class may have fields and methods used by objects solely to ensure their work (for example, a buffer in dynamic memory, a file with working data, methods for working with this file, etc.). Changing such fields or calling methods from outside the object is dangerous - this can disrupt its working state. To ensure the security of objects, such fields and methods can be hide- prohibit access to them from the outside.

From the standpoint of “fighting complexity,” encapsulation allows you to shift part of the control over the correct operation of objects to the compiler (computer).

Different TOEs offer different options for encapsulating fields and methods (from complete absence to automatic hiding of all fields). In industrial OML, such as C++, Java, Delphi, Eiffel, etc., there are three levels of encapsulation of fields and methods:

· public - to address public fields and there are no restrictions on object methods;

protected - direct access to protected fields and methods are possible only from methods of this class and methods of child classes;

private - direct access to private fields and methods are possible exclusively from methods of this class.

Inheritance

Inheritance- creating new classes by adding only differences from existing classes, omitting descriptions of matching elements. When inheriting, the new class is called child class(derived, child, subclass), and the original class is called ancestor class(base, parent, super class).

Inheritance reduces program size by eliminating duplicate declarations. All fields and methods declared in the ancestor class are automatically transferred to the descendant class, and they are usually called inherited(inherited).

If necessary, any parent method can be redefine- i.e. assign execution of another algorithm in case of calling a method of the same name in a descendant class.

Some OYs support multiple inheritance, in which a derived class inherits all properties and methods simultaneously from several classes. Unfortunately, multiple inheritance is fraught with many logical conflict situations, and its support complicates the programming language, and especially the compiler. For this reason, multiple inheritance is simply prohibited in many OOYs, but it can be simulated.

The set of all ancestor and descendant classes is called class hierarchy.

Class inheritance is the central concept of OOP; all other concepts and mechanisms are directly or indirectly based on it. The vast majority of OOP mechanisms require the construction of class hierarchies to demonstrate their benefits.

Polymorphism

Polymorphism(literally - “variety of forms”) - the ability to use one name for several methods (or functions) that have a similar purpose. Another interpretation is that one method (function) can have several implementation options; such a method (function) is called polymorphic. Like other OOP mechanisms, polymorphism is a means of simplifying the development of complex programs. In fact, polymorphism separates the concept What must be done because How this must be done.

If we draw an analogy with real life, then polymorphism corresponds to generalized actions. For example, the verb “to play music” means “to play a musical instrument.” But different musical instruments are played differently. There is one term, but many options for action. So, “play music” - polymorphic action. In OOP, the action “play music” would correspond to polymorphic method, which has its own implementations for each class of musical instruments.

There are two types of polymorphic methods in OOP - overloaded And virtual.

Overloaded Methods designed to perform with data of different types. They have the same names, but different argument lists and/or return types.

Virtual methods designed to perform operations that are identical in meaning in objects of related but not identical classes. Virtual methods have the same names and prototypes. Their main feature is that they always exactly correspond to the real class of the object.

A typical example of overloaded functions is the SQR function in Pascal. It calculates the square of a number, and for integer arguments the result will also be integer, and for real arguments it will be real.

The benefits of virtual methods only appear when using a class hierarchy. A typical use of virtual methods is as follows:

· In the ancestor class of the hierarchy, a polymorphic method is declared that describes some useful action. In this case, either it uses a virtual method, or it is itself virtual.

· In descendant classes, the corresponding virtual method is overridden - for each descendant class this useful action is performed in its own way.

· When you call a polymorphic method on an object belonging to a descendant class, the virtual method of the descendant class (and not the ancestor class) is actually used.

A striking example of this use of virtual methods is the Delphi or Visual Basic graphical window interface system: every visible element of the graphical interface is a button, slider, window, etc. - must be a descendant of the TControl class. The TControl class introduces common polymorphic methods for drawing GUI elements, and any of its descendants can draw themselves on the screen in their own way.

Object-oriented programming is not explicitly mentioned in the 2004 Standard, although such a topic was present in the Mandatory Minimum Content of Education in Computer Science for students of specialized institutions (Level B): Object-oriented programming: object, object properties, operations on an object. Object-oriented programming technology was also mentioned there.

Nevertheless, OOP has not only become part of the practice of teaching computer science (programming) in many schools, but is also present on the pages of school textbooks ( Ugrinovich N.D. Computer Science and information Technology. Textbook for grades 10–11, 2005. M.: BINOM. Laboratory of Knowledge). In addition, the concepts of object and him properties.

The technology (paradigm) of OOP requires not so much mastery modern technology programming, as much as the ability to develop an object model of the problem being solved. This requires a good knowledge of the basic principles of OOP and programming in general, but knowledge of any OOP is not mandatory - the founders and theorists of OOP have repeatedly written about this. Thus, Gradi Booch in his book “Object-Oriented Design and Analysis” expresses the following maxim: “You can write programs in an object-oriented style in any (non-object-oriented) programming language.” To build an algorithm using OOP technology, you need to generate a list of objects with which the algorithm works, think through the properties of each object, and implement the algorithm as an interaction of the described objects.

As already mentioned in the article, this approach simplifies the solution of complex problems, but within a school (given the limited number of hours) it is difficult to come up with meaningful learning tasks that would not contrivedly require the use of OOP technology to the fullest.

In fact, OOP in school is considered only as an integral part of visual and component programming in modern professional programming systems, and ready-made object libraries of various levels are used as objects - these are libraries for building a graphical interface for Windows applications, and multi-purpose universal data type libraries (for example , STL in C++). For primitive use of these libraries, it is enough to know and be able to apply a few simple rules of programming language syntax. However, such “knowledge” in no way brings students closer to professional mastery of a programming language, or even to an understanding of OOP. But, apparently, there is nothing wrong with that. School computer science, even in a specialized school, does not aim to train professional programmers. Teaching OOP is a special topic; even in the relevant specialties at universities, it is often not studied in sufficient detail.

Without completely denying the proposal of some computer science teachers to put the object-oriented approach at the forefront of studying programming, including at school, we note that OOP is impossible without such basic concepts as program, executor, variable, condition, loop, etc. The concept of OOP also includes classical procedural programming (see “ Subroutines”, like Einstein's mechanics - Newton's mechanics: it is enough to imagine a procedural program as a single object with the name omitted for simplicity. Therefore, first of all, the task of a programming course at school is to teach basic things. And only if it is possible to work with modern visual programming environments (Delphi, Visual Basic, Visual C++
etc.) introduce the concept of objects and their use mainly through the “model-based” programming teaching method.

(OOP) organizes the data and algorithms processed by the program. In this case, the programmer creates data forms and algorithms that correspond to the main characteristics of the problem being solved. Data models and algorithms that process them are called classes, A objects- these are their specific representatives used in the program.

From general objects, other, more specialized ones are created. The mechanism for creating such subobjects is called inheritance. As a result, these programs are object model- a tree of objects, starting with the top most abstract and general object.

OOP combines the best principles of structured programming with powerful new concepts, the basic ones being called encapsulation, polymorphism, and inheritance.

An example of object-oriented languages ​​are: Object Pascal , C++, Java.

OOP allows you to optimally organize programs by breaking a problem into its component parts and working with each separately.

Object-oriented programming is a development of structured programming technology, but it has its own characteristic features. The basic unit in object-oriented programming is an object, which contains and encapsulates both the data that describes it (properties) and the means for processing this data (methods). OOP systems typically use a graphical interface to visualize the programming process. It becomes possible to create objects, set their properties and behavior using the mouse.

An object is a combination of data and code. In other words, an object also called representative(of some class) is a piece of data, the value of which determines its current state, and a set of subroutines called methods operating with these data and defining behavior object, i.e. its reaction to external influences.

The object consists of the following three parts:

Object name;

State (state variables);

Methods (operations).

Each object is a representative (instance) of a certain class. During program execution, objects interact with each other by calling methods, which are subroutines specific to a particular class.

Class(class) is a group of data and methods (functions) for working with this data. This is a template. Objects with the same properties, that is, with the same sets of state variables and methods, form a class. An object is a concrete implementation, an instance of a class. In programming, the relationship between an object and a class can be compared to the description of a variable, where the variable itself (object) is an instance of some data type (class).


Object-oriented programming comes down to creating a certain number of classes, describing the relationships between these classes and their properties, and further implementing the resulting classes.

Theoretical approach. Class is one of the options for describing an entity, which in programming theory is called an abstract data type. A class defines the hidden internal structure of a value, as well as a set of operations that can be applied to that value.

Practical approach. In modern object-oriented programming languages ​​(php, Java, C++, Oberon, Python, Ruby, Smalltalk, Object Pascal), creating a class comes down to writing a structure containing a set of fields and methods. In practice, a class can be understood as a kind of template according to which objects—instances of a given class—are created. Instances of the same class are created using the same template, and therefore have the same set of fields and methods.

Relationships between classes:

Inheritance (Generalization) - objects of a child class inherit all properties of the parent class.

Association - objects of classes interact with each other.

Aggregation - objects of one class are included in objects of another.

Composition - objects of one class are included in objects of another and depend on each other in terms of their lifetime.

Class-Metaclass is a relationship in which other classes are instances of one class.

Types of classes:

Base (parent) class;

Derived class (successor, descendant);

Abstract class;

Virtual class;

Interface.

A class is a structural data type that includes a description of data fields, as well as procedures and functions that operate on these data fields. In relation to classes, such procedures and functions are called methods.

Methods- procedures and functions encapsulated in a class, that is, ways of working with data.

Classes and object-oriented programming are based on three principles: - encapsulation, inheritance And polymorphism.

Encapsulation(hiding) is a property of a programming language that allows you to combine data and code into an object and hide the implementation of the object from the user. In this case, the user is provided only with the specification (interface) of the object. The user can only interact with the object through this interface.

Most often, encapsulation is accomplished through information hiding, that is, masking all internal details that do not affect external behavior. Usually both the internal structure of an object and the implementation of its methods are hidden.

Encapsulation goals:

§ extreme localization of changes if such changes are necessary,

§ predictability of changes (what changes in the code need to be made for a given change in functionality) and predictability of the consequences of changes.

Encapsulation- this is the process of separating from each other the elements of an object that determine its structure and behavior. Often encapsulation can be achieved by simple organizational measures: knowing that “this is not something you can’t do” is sometimes the most effective means of encapsulation!

Encapsulation- combining records with procedures and functions that manipulate the fields of these records forms a new data type - an object.

Encapsulation- isolation of class components (fields, methods and properties) from other parts of the program.

The essence of encapsulation: Object state variables are hidden from the outside world. Changing the state of an object (its variables) is possible ONLY using its methods (operations). Why is this so important? This principle allows you to protect object state variables from misuse.

The use of this method leads to a decrease in the efficiency of access to object elements. This is due to the need to call methods to change the internal elements (variables) of the object. However, at the current level of development of computer technology, these losses in efficiency do not play a significant role.

Inheritance- one of the four most important mechanisms of object-oriented programming (along with encapsulation, polymorphism and abstraction), which allows you to describe a new class based on an already existing (parent), while the properties and functionality of the parent class are borrowed by the new class.

Inheritance- this is the process by which one object can inherit the properties of another object and add to them features characteristic only of it. The meaning and universality of inheritance lies in the fact that you do not need to describe a new object every time anew (from scratch), but you can specify the parent (base class) and describe distinctive features new class. As a result, the new object will have all the properties of the parent class plus its own distinctive features.

Inheritance- represents the possibility of constructing a hierarchy of objects using the inheritance of their characteristics.

Inheritance. Inheritance is a property of an object that allows it to use the fields and methods of the parent object, without describing them in its structure.

Inheritance- the ability to create new classes based on existing ones with the ability to use their components. An object belonging to a descendant class can use the fields, properties and methods of the parent class and new components of its class.

If a new method of the same name as a method of the parent class is described in a descendant class, then they say that the parent method is “overridden” in the descendant. In other words, a descendant class implements the specification of an already existing class (base class). This allows you to treat objects of a descendant class in the same way as objects of a base class. When creating a class hierarchy, some properties of objects, while maintaining names, change in essence.

To implement such hierarchies, the programming language provides polymorphism. The word polymorphism is of Greek origin and is translated as “having many forms.”

Polymorphism. Assigning a single name to an action, which is then shared down and up the hierarchy of objects, with each object in the hierarchy performing that action in a way that suits it.

Polymorphism is a property that allows the same name to be used to solve several technically different problems.

In OOP terms, we can say that all types of interface buttons have the ability to display themselves on the screen. However, the method (procedure) is different for each type of button. A simple button is drawn on the screen using the procedure “displaying an image of a simple button”, a toggle button is drawn on the screen using the procedure “displaying an image of a switch button”, etc.

Thus, there is a single action for the entire list of interface buttons (displaying the button image on the screen), which is implemented in a way specific to each button. This is a manifestation of polymorphism.

Polymorphism- the ability of classes to solve similar problems in different ways. When a parent method is overridden, a new algorithm for solving the problem is implemented in the child. It turns out that in the parent object and the child object there are two methods of the same name, which have a different algorithmic basis.

Polymorphism- this is a method of acting with a set of objects of the same ancestor in one step, without detailing operations with each specific object. It is also the basis for the extensibility of object-oriented programs because it provides a way for older programs to accept new data types that were not defined when the program was written.

In a general sense, the concept of polymorphism is the idea of ​​“one interface, many methods.” This means that you can create a common interface for a group of related actions.

Advantage Polymorphism is that it helps reduce program complexity by allowing a single interface to be used for a single class of actions. The choice of a specific action, depending on the situation, rests with the compiler.

In OOP, the goal of polymorphism is to use a single name to define actions common to a class. In practice, this means the ability of objects to select an internal procedure (method) based on the type of data received in the message.

The mechanism of OOP operation in such cases can be described something like this: when calling one or another class method, the method of the class itself is first looked for. If a method is found, it is executed and the search for this method ends. If the method is not found, then we turn to the parent class and look for the called method on it. If found, we proceed as if we found a method in the class itself. And if not, we continue further searching up the hierarchical tree. Up to the root (top class) of the hierarchy.

mob_info