Object-oriented programming (OOP) is currently the most popular programming technology. Object-oriented programming is a development of structured programming technology, but has its own characteristic features.
The most common object-oriented visual programming systems are Microsoft Visual Basic and Borland Delphi.
Object-oriented programming, at its core, is about creating applications from objects, just as houses are built from blocks and various parts. Some objects have to be created entirely on your own, while others can be borrowed ready-made from various libraries.
An important place in object-oriented programming technology is occupied by event. Events can be a mouse click on an object, pressing a certain key, opening a document, etc. As a reaction to events, a certain procedure is called, which can change the properties of the object, call its methods, etc.
Object-oriented programming 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, on the one hand, has certain properties that characterize its state at a given moment in time, and, on the other hand, operations are possible that lead to changes in properties.
The basic unit in object-oriented programming is an object that encapsulates both the data that describes it (properties) and the means for processing this data (methods).
Encapsulation is the union of an object's properties and possible operations (methods) on it.
Another principle underlying OOP is the possibility of creating a new class of objects with inheritance of properties and methods of some already existing class.
Inheritance is the ability to derive one class from another while preserving all the properties and methods of the ancestor class (progenitor, sometimes called a superclass) and adding, if necessary, new properties and methods.
A set of classes related by inheritance is called a hierarchy. Inheritance is intended to reflect such a property of the real world as hierarchy.
Another principle of OOP is the principle of polymorphism.
Polymorphism is the phenomenon in which a function (method) with the same name corresponds to different program code (polymorphic code) depending on which class object is used when calling this method.
Polymorphism is ensured by changing the implementation of the method of the ancestor class in the descendant class with the obligatory preservation of the method signature. This ensures that the interface of the ancestor class remains unchanged and allows you to associate the method name in the code with different classes - from the object of which class the call is made, from that class the method with the given name is taken. This mechanism is called dynamic (or late) linking - as opposed to static (early) linking, which is carried out at compile time
The object-oriented approach allows you to combine a static model that describes the properties of an object and a dynamic model that describes their changes.
With this approach, access to changing the properties of an object is possible only through methods belonging to this object. Methods "surround" the properties of an object; properties are said to be "encapsulated" in an object.
Thus, in object-oriented programming, a central place is occupied by objects that combine into one whole (encapsulate) the properties of an object and the operations (methods) possible on it.
Objects that encapsulate the same list of properties and operations are combined into classes. Each individual object is an instance of the class. Instances of a class can have different property values.
For example, a computer's file system may contain hundreds or thousands of files. All files have the same set of properties (name, position in the file system, etc.) and operations (renaming, moving or copying, etc.) and form a class of objects Files.
Each individual file is an instance of this class and has specific property values (name, location, etc.).
A situation often occurs when the same operations can be performed on objects of different classes. Most classes of objects in the Windows environment (folders, documents, symbols, etc.) are also characterized by a set of the same operations (renaming, moving, copying, deleting, etc.). This uniformity is very user friendly.
However, it is obvious that the mechanisms for implementing these operations are not the same for different classes. For example, to copy a folder, you need to perform a sequence of actions to change the file system, and to copy a symbol, make changes to the document. These operations will be performed by various programs that are available, respectively, in the Windows operating system and in the Word text editor.
In this way it is realized polymorphism, those. the ability to perform the same operations on objects belonging to different classes, while maintaining individual methods for their implementation for each class.
Objects that have the same sets of properties and methods form object class. So, in the Word application there is an object class document(Documents), which has the following properties: Name(Name), locationtion(FileNaine), etc. Objects of this class also have a certain set of methods, for example: opening a documentcop(Open) document printing(Printout), preservationdocument(Save), etc.
Objects in applications form some kind of hierarchy. At the top of the object hierarchy is application(Application). Thus, the Word application object hierarchy includes the following objects: application(Application), document(Documents), document fragment(Selection), symbol(Character), etc.
The Excel application object hierarchy includes the following objects: application(Application), book(Workbook), sheet(Worksheet) cell range(Range), cellska(Cell), etc.
A full reference to an object consists of a series of names of objects nested sequentially within each other. The separators for object names in this series are dots; the series begins with the highest-level Application object and ends with the name of the object of interest to us. For example, a link to the document Пpo6a.doc in Word will look like this:
Application. Documents("Ppo6a.doc")
In order for an object to perform any operation, a method must be specified. Many methods have arguments that allow you to specify parameters for the actions to be performed. To assign specific values to arguments, a colon and an equal sign are used, and arguments are separated by a comma.
In Visual Basic, objects are characterized not only by properties and methods, but also events. An event is an action recognized by an object. An event can be generated by the user (for example, pressing a mouse button or a key on the keyboard) or be the result of the operation of other application objects.
For each event, you can program a response, that is, the object’s reaction to the event that occurred. This program is called event procedure. The name of an event procedure is usually composed of the name of the object and the name of the event. For example, for a button object named Command1 and events Click(“click” that occurs when we move the mouse cursor over the button image and press the left mouse button) the event procedure will receive the name Command1_ Click.
Several objects can participate in an event procedure. For example, in the procedure mentioned above Command1_ Click team may be present
Text1. Text= “Hello!”,
as a result of executing which in the “text field” object with the name Text1 A line with the word “Hello!” will appear.
Visual programming, the methods of which are used by the Visual Basic development environment, allows you to create a graphical interface for developed applications based on the use of control elements, which include buttons(CommandButton), checkboxes(CheckBox) , text fields(TextBox) combo boxes(ListBox) and others. These objects, their properties and methods will be discussed in the next section. For now, let’s just note that control elements are most often used to receive data from the user and display the results of the application. Thus, controls are the basis for building the user interface of the application.
The main objects used in visual programming are forms(Form). A form is a window on which control elements are placed. A form is also an object characterized by a set of properties and methods. As with any other object, you can write an event procedure for a form, for example Form_ Load, which is launched when the Load event occurs and as a result of which the instructions necessary for the operation of the launched application will be executed.
essentially used the prescriptive programming paradigm - the goal was to create code that acted appropriately on the data. This approach is good for solving small problems, but it creates many intractable problems when trying to create large software systems.One of the alternatives directive programming is object-oriented programming, which really helps to cope with the nonlinearly growing complexity of programs as their volume increases. One should not, however, conclude that using the object-oriented programming paradigm guarantees a successful solution to all problems.
In order to become a professional in programming, you need talent, creativity, intelligence, knowledge, logic, the ability to build and use abstractions and, most importantly, experience.
In this section, we will continue our introduction to the basic concepts of object-oriented programming, which we began in the first chapter of the book. First, OOP concepts common to various programming languages will be discussed, and then their implementation in the Java language.
You should be aware that the course on object-oriented programming is taught to undergraduate students over the course of an entire semester, and therefore the material presented below represents only a very basic introduction to the world of OOP. A much more complete treatment of many of the issues related to object-oriented design, engineering, and programming is contained in the book, and in the third chapter of the book you can find a very clear description of all object-oriented aspects of the Java language.
Object-oriented programming or OOP (object-oriented programming) - programming methodology based on the representation of a program as a collection of objects, each of which is an implementation of a certain type, using a mechanism forwarding messages and classes organized in inheritance hierarchy.
The central element of OOP is abstraction. Data is converted into objects using abstraction, and the sequence of processing this data turns into a set of messages passed between these objects. Each of the objects has its own unique behavior. Objects can be treated as concrete entities that respond to messages commanding them to perform some action.
OOP is characterized by the following principles (according to Alan Kay):
Definition 10.1. Abstraction- a method of solving a problem in which objects of various kinds are united by a common concept (concept), and then the grouped entities are considered as elements of a single category.
Abstraction allows you to separate the logical meaning of a program fragment from the problem of its implementation, dividing external description(interface) of an object and its internal organization(implementation).
Definition 10.2. Encapsulation- a technique in which information that is insignificant from the point of view of the object’s interface is hidden inside it.
Definition 10.3. Inheritance- a property of objects through which instances of a class gain access to the data and methods of ancestor classes without redefining them.
Inheritance allows different data types to share the same code, resulting in smaller code and greater functionality.
Definition 10.4.
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.
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.
Hello! Have you ever wondered why Java is designed the way it is? In the sense that you create classes, based on them - objects, classes have methods, etc. But why is the structure of the language such that programs consist of classes and objects, and not of something else? Why was the concept " an object” and put at the forefront? Do all languages work this way and, if not, what benefits does it give Java? As you can see, there are a lot of questions :) Let's try to answer each of them in today's lecture.
It would seem that, Simula- an ancient language by programming standards, but their “family” connection with Java is visible to the naked eye. Most likely, you can easily read the code written on it and explain in general terms what it does :) Begin Class Rectangle (Width, Height) ; Real Width, Height; Begin Real Area, Perimeter; Procedure Update; Begin Area : = Width * Height; OutText( "Rectangle is updating, Area = ") ; OutFix(Area, 2, 8); OutImage; Perimeter : = 2 * (Width + Height) ; OutText( "Rectangle is updating, Perimeter = ") ; OutFix(Perimeter, 2, 8); OutImage; End of Update; Update; OutText("Rectangle created: "); OutFix(Width, 2, 6); OutFix(Height, 2, 6); OutImage; End of Rectangle; Rectangle Class ColoredRectangle(Color); Text Color; Begin OutText ( "ColouredRectangle created, color = ") ; OutText(Color); OutImage; End of ColoredRectangle; Ref(Rectangle)Cr; Cr: - New ColoredRectangle(10, 20, "Green"); End; The code example is taken from the article Simula - 50 years of OOP. As you can see, Java and its ancestor are not so different from each other :) This is due to the fact that the appearance of Simula marked the birth of a new concept - object-oriented programming. Wikipedia gives the following definition of OOP: Object-oriented programming (OOP) - a programming methodology based on representing a program as a collection of objects, each of which is an instance of a specific class, and the classes form an inheritance hierarchy. It is, in my opinion, very successful. You recently started learning Java, but there are hardly any words in it that are unfamiliar to you :) Today OOP- the most common programming methodology. Besides Java, they are used in many popular languages that you may have heard of. These are C++ (it is actively used by computer game developers), Objective-C and Swift (they write programs for Apple devices), Python (most in demand in machine learning), PHP (one of the most popular web development languages), JavaScript (simpler say what they don’t do on it) and many others. Actually, what are these “principles” of OOP? Let's tell you in more detail.
Probably half of the vacancies (if not more) require knowledge and understanding of OOP. Yes, this methodology has definitely captivated many programmers! Usually, understanding OOP comes with experience, since there are practically no suitable and accessible materials on this subject. And even if there are, it is far from certain that readers will stumble upon them. I hope I will be able to explain the principles of this wonderful methodology, as they say, on my fingers.
So, already at the beginning of the article I already mentioned the term “methodology”. When applied to programming, this term implies the presence of any set of ways to organize code, methods of writing it, adhering to which, the programmer will be able to write completely usable programs.
OOP (or object-oriented programming) is a way of organizing program code where the main building blocks of the program are objects and classes, and the logic of the program is built on their interaction.
About objects and classes
Class- this is a data structure that can be created by the programmer himself. In OOP terms, a class consists of fields(in simple terms - variables) and methods(in simple terms - functions). And, as it turned out, the combination of data and functions for working on it in one structure gives unimaginable power. An object is a specific instance of a class. Following the analogy of a class with a data structure, an object is a specific data structure that has some values assigned to its fields. Let me explain with an example:
Let's say we need to write a program that calculates the perimeter and area of a triangle, which is given by two sides and the angle between them. To write such a program using OOP, we will need to create a class (that is, a structure) Triangle. The Triangle class will store three fields (three variables): side A, side B, the angle between them; and two methods (two functions): calculate the perimeter, calculate the area. With this class we can describe any triangle and calculate the perimeter and area. So, a specific triangle with specific sides and an angle between them will be called an instance of the Triangle class. Thus, a class is a template, and an instance is a concrete implementation of the template. But instances are objects, that is, specific elements that store specific values.
One of the most common object-oriented programming languages is java. There you simply cannot do without using objects. This is what the code for a class describing a triangle in this language would look like:
/** * Triangle class. */ class Triangle ( /** * Special method called class constructor. * Takes three parameters as input: * length of side A, length of side B, * angle between these sides (in degrees) */ Triangle(double sideA, double sideB , double angleAB) ( this.sideA = sideA; this.sideB = sideB; this.angleAB = angleAB; ) double sideA; //Class field, stores the value of side A in the described triangle double sideB; //Class field, stores the value of the side B in the described triangle double angleAB; //Class field stores the angle (in degrees) between two sides in the described triangle /** * Class method that calculates the area of the triangle */ double getSquare() ( double square = this.sideA * this .sideB * Math.sin(this.angleAB * Math.PI / 180); return square; ) /** * Class method that calculates the perimeter of a triangle */ double getPerimeter() ( double sideC = Math.sqrt(Math.pow (this.sideA, 2) + Math.pow(this.sideB, 2) - 2 * this.sideA * this.sideB * Math.cos(this.angleAB * Math.PI / 180)); double perimeter = this.sideA + this.sideB + sideC; return perimeter; ) )
If we add the following code inside the class:
/** * This is where the program runs */ public static void main(String args) ( //Values 5, 17, 35 go into the Triangle class constructor Triangle triangle1 = new Triangle(5, 17, 35); System.out .println("Area of triangle1: "+triangle1.getSquare()); System.out.println("Perimeter of triangle1: "+triangle1.getPerimeter()); //Values 6, 8, 60 go to the Triangle class constructor Triangle triangle2 = new Triangle(6, 8, 60); System.out.println("Area of triangle1: "+triangle2.getSquare()); System.out.println("Perimeter of triangle1: "+triangle2.getPerimeter()); )
then the program can already be launched for execution. This is a feature of the java language. If the class has such a method
Public static void main(String args)
then this class can be executed. Let's look at the code in more detail. Let's start with the line
Triangle triangle1 = new Triangle(5, 17, 35);
Here we create an instance of triangle1 of the Triangle class and immediately give it the parameters of the sides and the angle between them. At the same time, a special method called the constructor is called and fills the fields of the object with the values passed to the constructor. Well, what about the lines?
System.out.println("Area of triangle1: "+triangle1.getSquare()); System.out.println("Perimeter of triangle1: "+triangle1.getPerimeter());
output the calculated area of the triangle and its perimeter to the console.
The same thing happens for the second instance of the Triangle class.
Understanding the essence of classes and the construction of concrete objects is a confident first step to understanding OOP methodology.
Once again, the most important thing:
OOP- this is a way of organizing program code;
Class- this is a custom data structure that brings together data and functions for working with them (class fields and class methods);
An object is a specific instance of a class whose fields are given specific values.
Three magic words
OOP includes three key approaches: inheritance, encapsulation and polymorphism. To begin with, I will give definitions from wikipedia:
Encapsulation is a system property that allows you to combine data and methods that work with them in a class. Some languages (eg C++) equate encapsulation with hiding, but most (Smalltalk, Eiffel, OCaml) distinguish between these concepts.
Inheritance is a system property that allows you to describe a new class based on an existing one with partially or completely borrowed functionality. The class from which inheritance is derived is called the base, parent, or superclass. A new class is a descendant, heir, child, or derived class.
Polymorphism is a system property that allows you to use objects with the same interface without information about the type and internal structure of the object.
Understanding what all these definitions actually mean is quite difficult. In specialized books that cover this topic, each definition often devotes a whole chapter, but at least a paragraph. Although, the essence of what a programmer needs to understand and imprint forever in his brain is very little.
And as an example for analysis, we will use figures on a plane. From school geometry we know that for all figures described on a plane, it is possible to calculate the perimeter and area. For example, for a point both parameters are equal to zero. For a segment, we can only calculate the perimeter. And for a square, rectangle or triangle - both. Now we will describe this task in OOP terms. It is also a good idea to grasp the chain of reasoning that results in a class hierarchy, which, in turn, is embodied in working code. Go:
So, a point is the smallest geometric figure, which is the basis of all other constructions (figures). Therefore, the point was chosen as the base parent class. Let's write a point class in Java:
/** * Point class. Base class */ class Point ( /** * Empty constructor */ Point() () /** * Class method that calculates the area of a figure */ double getSquare() ( return 0; ) /** * Class method that calculates the perimeter of the figure */ double getPerimeter() ( return 0; ) /** * Class method that returns a description of the figure */ String getDescription() ( return "Point"; ) )
The resulting Point class has an empty constructor, since in this example we are working without specific coordinates, and operating only with parameters and side values. Since the point has no sides, there is no need to pass any parameters to it. Also note that the class has methods Point::getSquare() and Point::getPerimeter() for calculating area and perimeter, both return 0. For a point it is logical.
Since our point is the basis of all other figures, we inherit the classes of these other figures from the Point class. Let us describe the class of a segment inherited from the class of a point:
/** * Class Line Segment */ class LineSegment extends Point ( LineSegment(double segmentLength) ( this.segmentLength = segmentLength; ) double segmentLength; // Length of the line /** * Overridden class method that calculates the area of the line */ double getSquare( ) ( return 0; ) /** * Overridden class method that calculates the perimeter of a segment */ double getPerimeter() ( return this.segmentLength; ) String getDescription() ( return "Segment length: " + this.segmentLength; ) )
Class LineSegment extends Point
means that the LineSegment class inherits from the Point class. The LineSegment::getSquare() and LineSegment::getPerimeter() methods override the corresponding base class methods. The area of a segment is always zero, and the area of the perimeter is equal to the length of this segment.
Now, similar to the segment class, we will describe the triangle class (which also inherits from the point class):
/** * Triangle class. */ class Triangle extends Point ( /** * Class constructor. Takes three parameters as input: * length of side A, length of side B, * angle between these sides (in degrees) */ Triangle(double sideA, double sideB, double angleAB ) ( this.sideA = sideA; this.sideB = sideB; this.angleAB = angleAB; ) double sideA; //Class field, stores the value of side A in the described triangle double sideB; //Class field, stores the value of side B in the described triangle triangle double angleAB; //Class field that stores the angle (in degrees) between two sides in the described triangle /** * Class method that calculates the area of a triangle */ double getSquare() ( double square = (this.sideA * this.sideB * Math.sin(this.angleAB * Math.PI / 180))/2; return square; ) /** * Class method that calculates the perimeter of a triangle */ double getPerimeter() ( double sideC = Math.sqrt(Math. pow(this.sideA, 2) + Math.pow(this.sideB, 2) - 2 * this.sideA * this.sideB * Math.cos(this.angleAB * Math.PI / 180)); double perimeter = this.sideA + this.sideB + sideC; return perimeter; ) String getDescription() ( return "Triangle with sides: " + this.sideA + ", " + this.sideB + " and angle between them: " + this.angleAB; ) )
There's nothing new here. Also, the Triangle::getSquare() and Triangle::getPerimeter() methods override the corresponding methods of the base class.
Well, now, in fact, the very code that shows the magic of polymorphism and reveals the power of OOP:
Class Main ( /** * This is where the program runs */ public static void main(String args) ( //ArrayList - This is a special data structure in java // that allows you to store objects of a certain type in an array. ArrayList figures = new ArrayList (); //add three different objects to the figures array figures.add(new Point()); figures.add(new LineSegment(133)); figures.add(new Triangle(10, 17, 55)); for ( int i = 0;i
We have created an array of objects of the Point class, and since the LineSegment and Triangle classes inherit from the Point class, we can place them in this array. It turns out that we can consider each figure that is in the figures array as an object of the Point class. This is what polymorphism is: it is not known which class the objects in the figures array belong to, but since all the objects inside this array belong to the same base class Point, then all methods that are applicable to the Point class are also applicable to its descendant classes.
Now about encapsulation. The fact that we placed the parameters of a figure and methods for calculating area and perimeter in one class is encapsulation; we encapsulated the figures into separate classes. The fact that we use a special method in the class to calculate the perimeter is encapsulation; we encapsulated the calculation of the perimeter in the getPerimiter() method. In other words, encapsulation is hiding the implementation (perhaps the shortest, and at the same time, capacious definition of encapsulation).
Full example code:
Import java.util.ArrayList; class Main ( /** * This is where the program runs */ public static void main(String args) ( //ArrayList is a special data structure in java // that allows you to store objects of a certain type in an array. ArrayList figures = new ArrayList (); //add three different objects to the figures array figures.add(new Point()); figures.add(new LineSegment(133)); figures.add(new Triangle(10, 17, 55)); for ( int i = 0;i