OOP classes. Object Oriented Programming

Table of contents:

OOP classes. Object Oriented Programming
OOP classes. Object Oriented Programming
Anonim

The terms "object" and "class" are familiar to everyone. However, for computer scientists, they have their own subtext. These are the basic concepts in object-oriented programming. Classes are a type of data defined by the developer, which is characterized by the way they are transferred and stored, the usage profile, and the set of actions that can be performed with them. They differ in that they can be implemented as an interface.

What is OOP (Object Oriented Programming)

Experienced developers are well versed in COBOL and C. The programs written in them were a sequence of step-by-step instructions. They used procedures and functions to make the program modular. This paradigm focused on logic, not data, and methods for putting them together.

Object Oriented Programming Classes
Object Oriented Programming Classes

Modern programming languages Delphi, Java, C and others follow an object-oriented approach. In this case, the importance is given to the data, and not just writing instructions to complete the task. An object is a thing or an idea that you wantsimulate. It can be anything, such as an employee, a bank account, a car, various furnishings, and so on.

The concept of object-oriented programming (OOP) is inherently related to the following criteria:

  • Abstraction.
  • Encapsulation.
  • Inheritance.
  • Polymorphism.

Let's look at each of them in more detail.

Abstraction

This criterion allows you to focus on what the object itself does, but not on how these actions are implemented in programming. OOP implies that abstraction is the knowledge about the object of the maximum amount of data. It helps in creating independent modules that can interact with each other in some ways.

We try to selectively focus only on things that are important to us (in life) or to our module (in programming). Changing one independent module does not affect the others. The only thing to know is what he gives us. The person who uses this module should not worry about how the task is solved, what exactly is happening in the background.

C class constructor
C class constructor

The everyday objects we use have abstractions applied at different levels. One example of object-oriented programming is the application of braking in a car. This system is abstract: it is enough for a motorist to press the pedal for the vehicle to slow down and stop. Making changes to the systemacceleration does not affect the braking system, as they are independent. The driver does not need to understand the inner workings of the brakes. He only needs to press the pedal in time. In this case, the brake (both disc and drum) will work, and the car will slow down.

Encapsulation

This concept is closely related to abstraction. Encapsulation is the disclosure of a solution to a problem without requiring the user to fully understand the problem domain. It binds data and behavior together and prevents the client or user of the module from knowing about the internal representation that implements the abstraction behavior.

Object Oriented Programming System
Object Oriented Programming System

Data not available directly. They are accessed through certain functions. Hiding the internals of an object protects its integrity by preventing users from setting the component's internals to an invalid or incompatible state.

Inheritance

This is a code reuse mechanism that can help reduce code duplication. This concept is a powerful feature of object-oriented programming languages. It helps to organize classes into a hierarchy, allowing them to inherit attributes and behavior from components above them.

An example of inheritance: a parrot is a bird, the Russian ruble is a type of currency. However, the phrase "a bank is a bank account" is not correct. This connection is obvious when it is required to describe some entity in a given problem statement. Using inheritance, you can define a common implementationOOP and its behavior, and then for specialized classes to redefine or change these indicators to something more specific. Inheritance doesn't work backwards. The source (so-called parent) will not have the properties of the derived (child) class.

It's important to note that when trying to model a solution, don't add multiple levels of inheritance. One should try to identify common attributes and behaviors in the objects that are being modeled. Then, based on this, you can continue to refactor the code that determines the appropriate parent class. The general implementation can be moved into it.

Polymorphism

This concept allows you to expand computer systems by creating new specialized objects. At the same time, it allows the current version to interact with the new one, regardless of its specific properties.

For example, if the task is to write a message on a piece of paper, you can use a pen, pencil, marker or pen. It is enough that the tool can fit in the hand and be able to leave a mark when it comes into contact with the paper. It turns out that certain actions of a person make an inscription on a sheet, and what tool is used is not so important for transmitting information.

Another example of polymorphism in an object-oriented programming system is an airplane and a space shuttle, which can be called flying objects. How exactly do they move in space? Of course, there is a big difference in their work. That is, the ways of implementing their movement are not the same. However, from the viewer's point of view, both objects are flying.

OOP implementation
OOP implementation

Inheritance is one way to achieve polymorphism, where the behavior defined in an inherited class can be overridden by writing a custom method implementation. This is called overriding (compile-time polymorphism).

There is another form of polymorphism, called overloading, that does not respect inheritance. The method name will be the same, but the arguments in the method are different.

Features of the concepts "class" and "object"

To get started with object-oriented programming, we need to understand what an OOP class and an object are. It is important to understand the difference between them. A class is a blueprint for creating an object. It defines attributes and behavior. It's like an engineering drawing of a house. An object is an instance of a class. Here is the difference between them. The example below shows how the class "TForml" and the variable "Forml" are declared in the Delphi programming language:


type TForml=class(TForm) Buttonl: TButton; procedure ButtonlClick(Sender: TObject); end; var Form: TForml;

If we want to model, for example, a car in our program, we must define its attributes: model, fuel, brand, color, its behavior, as well as the so-called methods: starting the engine, braking, accelerating, and so on. It is clearly seen that these indicators are typical not only for one brand or model of vehicle.

When object-In the oriented approach, we are trying to generalize our object (machine) by stating that the one we are going to model in our program will have a number of attributes and methods. There may be other indicators and characteristics of the vehicle, but these are enough for us to understand how the class works in OOP.

When we use this data, we create a car with specific parameters. By programming the same object (machine), we can take different characteristics, as shown in the table below:

Object 1 Object 2
model: VAZ 2107 model: VAZ 2109
fuel: Gasoline fuel: Diesel
color: Red color: Green
engine start method: Start () engine start method: Start ()
braking method: Break () braking method: Break ()
acceleration method: Acceleration () acceleration method: Acceleration ()

Thus, object-oriented programming makes it easy to model the behavior of a complex real-world system. With OOP, data and functions (attributes and methods) are combined in an object. This prevents the need for any shared or global data with OOP. This approach is the main difference between object-oriented and procedural approaches.

What is a class in OOP
What is a class in OOP

OOP classes are made up of different types of elements:

  1. Data fields: store the state of the class using variables and structures.
  2. Methods: routines for manipulating specified data.
  3. Some languages allow a third type, properties. It's somewhere between the first two.

Methods

The behavior of a class or its instances is defined using methods. These are subroutines with the ability to operate on objects. These operations can change the state of an object or simply provide ways to access it.

There are many methods. Their support varies by language. Some are created and called by the programmer's code, others (special ones such as constructors, destructors, and conversion operators) are created and called by compiler-generated code. The language may allow the programmer to define these special methods.

Interface

This is the definition of a group of abstract actions. It figures out what behavior a certain object should exhibit without specifying how it should be implemented.

An object can have multiple roles and users can use it from different perspectives. For example, an object of type "person" can have roles:

  • Soldier (with "shoot the enemy" behavior).
  • Husband (with "love your wife" behaviour).
  • Taxpayer (with "pay taxes" behavior) and so on.

However, each object implements its behavior in its own way: Misha pays taxes on time, Andrey is late, and Peter doesn't do it at all. The same can be said abouteach object and other roles.

What is OOP
What is OOP

The question arises why the base class of all objects is not an interface. The reason is that in such a case, each class would have to implement a small but very important group of methods, which would take an unnecessary amount of time. It turns out that not all classes need a specific implementation - a generic default is enough in most cases. There is no need to override any methods, but if the situation requires it, it is possible to implement overriding them.

The buttons on the front of the TV are a good example. We can say that they are the interface between the user and the electrical wiring on the other side of the instrument case. A person presses the power button to turn an electrical appliance on and off. In this example, a specific TV is an instance, each method is represented by a button, and together they make up an interface. In its most common form, it is a specification of a group of related methods without their implementation.

Constructor

This criterion is responsible for preparing the object for action, for example, setting initial values for all its data and their elements. Although it has a special role, a constructor is just another function that can be used to pass information through an argument list. They can be used to initialize it. The name of the constructor function and the class are the same.

The following example explains the concept of a class constructor in C++ (a common programming language):


include using namespace std; class Line { public: void setLength(double len); double getLength(void); line(); // Constructor declaration private: double length; }; // Define functions, including constructor Line::Line(void) { cout << "Object created" << endl; } void Line::setLength(double len) { length=len; } double Line::getLength(void) { return length; } // Program body int main() { Line line; // Line length line.setLength(6.0); cout << "Length of line: " << line.getLength() <<endl; return 0; }

When the above code is compiled and executed, it produces the following result:

Object created

Length of line: 6

Destructor

This is a special class function that destroys an object as soon as its scope ends. The destructor is automatically called by the compiler when the object goes out of scope.

The syntax for a destructor is the same as for a constructor, however the class name is used here with a tilde character "~" as a prefix.

The following C++ example explains the concept of a destructor:


include using namespace std; class Line { public: void setLength(double len); double getLength(void); line(); // Constructor declaration ~Line(); // Destructor declaration private: double length; } // Define functions, including constructor Line::Line(void) { cout << "Object created" << endl; } Line::~Line(void) { cout << "Objectdeleted" << endl; } void Line::setLength(double len) { length=len; } double Line::getLength(void) { return length; } // Program body int main() { Line line; // Line length line.setLength(6.0); cout << "Length of line: " << line.getLength() <<endl; return 0; }

When the above code is compiled and executed, it will produce the following output:

Object created

Length of line: 6

Object deleted

What are the advantages of classes

The benefits of organizing software into object classes fall into three categories:

  • Rapid development.
  • Ease of maintenance.
  • Code and design reuse.
Basic concepts of object-oriented programming
Basic concepts of object-oriented programming

Classes and OOP in general promote rapid development because they reduce the gap between code and users. This was appreciated by many programmers. With this system, analysts can communicate with both developers and users using the same vocabulary, talking about accounts, customers, invoices, and so on.

Object classes often encourage rapid development because most object-oriented environments have powerful debugging and testing facilities. Class instances can be checked at runtime to make sure the system is working properly. Also, instead of taking kernel memory dumps, most object-oriented frameworks interpretdebugging capabilities. As a result, developers can analyze exactly where the error occurred in the program and see which methods, arguments, and values were used.

Popular topic

Editor's choice

  • The PHP mail function: description, application features
    The PHP mail function: description, application features

    E-mail is an integral part of any modern project or business. Nowadays, speed and responsiveness are of great value, especially when it comes to customer feedback. This is a decisive factor that users consider when making purchases

  • Shareware - what is it List of programs, description of programming principles
    Shareware - what is it List of programs, description of programming principles

    Shareware has battled the stigma of misunderstanding for decades. While enterprise software giants can no longer ignore the marketing potential of a trial, small startups still struggle with new software challenges and costs

  • What is var in Pascal
    What is var in Pascal

    Variable var is a name that the user assigns to computer memory cells and uses to store values in a computer program. It defines the type of information stored, describes the format of the value of the occupied memory and methods for manipulating the content

  • Java library: creating, processing, working with files
    Java library: creating, processing, working with files

    Experienced Java developer has extensive knowledge of APIs including JDK, libraries for everyday projects including Log4j, JSON parsing, Jackson. The problem is that not all Java library designers think about their users, how the API will be used in practice, and how the code will look and be tested

  • Compression algorithms: description, basic techniques, characteristics
    Compression algorithms: description, basic techniques, characteristics

    Currently, processor processing power is increasing faster than storage capacity and network bandwidth. Therefore, in order to compensate for the increase in the amount of data, they compress them. The compressor uses an optimization algorithm of the appropriate type. For subsequent recovery, a decompressor with the opposite direction of the process is required