Code

OOP Basics: Object-Oriented Programming Principles with Simple Examples

OOP Basics: Object-Oriented Programming Principles with Simple Examples

Where to start your journey in IT? Get a detailed guide in our Telegram channel for free! Click on the banner and visit the channel – you'll find the guide pinned.

Learn More

In this article, we'll begin a series of materials dedicated to object-oriented programming (OOP). The goal of this material is a deep understanding of the fundamentals of this development paradigm, not just mastering practical skills in working with classes and objects. We'll cover key OOP concepts and principles, such as encapsulation, inheritance, and polymorphism, to help you better master this important area of ​​programming.

The series includes articles dedicated to various aspects of object-oriented programming (OOP). These materials examine key OOP concepts, such as encapsulation, inheritance, polymorphism, and abstraction. Each article details the theoretical foundations and practical examples of using these principles in modern programming languages. In addition, the materials cover best practices for designing classes and objects, and discuss typical mistakes that can occur when working with OOP. The goal of the series is to deepen the understanding of the object-oriented approach and help developers effectively apply it in their projects.

  • What are classes and objects;
  • Features of working with objects;
  • Access modifiers, encapsulation;
  • Method overloading;
  • Polymorphism;
  • Inheritance and a little more polymorphism;
  • Abstract classes and interfaces;
  • Practical training.

All examples in this series are presented in C#. They focus on game development, since the gaming industry, like other areas, actively uses objects. Using objects in programming allows you to create more structured and scalable applications, which is especially important in game development.

Before you begin learning object-oriented programming (OOP), it is important to have a basic understanding of the following key concepts:

  • variables and data types
  • conditionals
  • loops
  • collections (preferred).

The work will be performed in the Visual Studio 2019 development environment, but it is also acceptable to use Visual Studio 2017. Both versions provide the necessary tools and features for effective programming and development.

Each article will include tasks to help reinforce the material covered. Although completing these tasks is optional, it is important to understand that mastering object-oriented programming (OOP) is impossible without practice. If you do not want to complete the tasks, you can always check out our solution options. Let's get started!

Object-oriented programming (OOP) is a software development methodology based on the use of objects, which are instances of classes. The primary goal of OOP is to create more structured and modular code, making it easier to maintain and evolve. Key OOP concepts include encapsulation, inheritance, and polymorphism. Encapsulation allows you to hide the internal implementation details of an object and provide users with only the necessary interfaces. Inheritance allows you to create new classes based on existing ones, promoting code reuse. Polymorphism allows you to use objects of different classes through a single interface, making your code more flexible and adaptable. OOP is widely used in modern programming languages ​​such as Java, C++, Python, and many others, and is the foundation for developing complex software systems. Understanding the principles of object-oriented programming is an important step for every developer striving to create high-quality and efficient software.

  • What is OOP
  • What are its pros and cons
  • What are abstraction, encapsulation, inheritance and polymorphism
  • Objects and classes: how to use them
  • How to create a class
  • How to use class fields and properties
  • How to create a method
  • What is an object constructor
  • Homework
  • What to remember

What is OOP

Object-oriented programming (OOP) is a software development paradigm in which the fundamental building blocks are objects. These objects combine data and the methods that operate on it, allowing you to create more structured and flexible applications. OOP promotes code reuse, improves its organization, and simplifies the maintenance of software solutions. The main principles of OOP include encapsulation, inheritance, and polymorphism, making this paradigm one of the most popular in modern programming.

Objects and classes are the main concepts of object-oriented programming (OOP). It is important to clearly understand their differences. A class can be thought of as a template or blueprint that defines the properties and behavior of objects. An object, in turn, is a concrete implementation of this class, possessing unique attribute values. Understanding these differences allows you to more effectively apply OOP principles in software development.

A class is a user-defined data type that includes various properties and methods, similar to built-in types such as String or Int. Classes are the foundation of object-oriented programming and allow you to create complex data structures, providing convenience and flexibility in software development.

An object is an instance of a class that is stored in the computer's RAM. For example, when you create a String variable and assign it the value "String," an instance of the String class is created in memory. This allows you to use the methods and properties defined in the class to manipulate the data. Objects play a key role in object-oriented programming, providing encapsulation and organized data management.

Objects represent entities with specific properties and behavior. They are most often instances of classes. For example, in a game, there is a Character class, instances of which can be objects such as a hero or an NPC (non-player character). This structure allows you to organize your code, providing clarity and making it easier to manage the various elements of your game.

Our class is a "skeleton". With it, we can create different characters: heroes or NPCs. Infographic: Olya Yezhak / Skillbox Media

Properties represent information associated with a specific object. This data helps describe and characterize the object, defining its unique qualities and features. Properties can include parameters such as size, color, material, and other characteristics that allow users to better understand the object and its purpose. Understanding the properties of objects is key in various fields such as programming, design, and marketing, as it allows for more accurate representation and use of objects in the appropriate context.

  • health,
  • points,
  • money,
  • strength,
  • agility,
  • intelligence,
  • speed,
  • coordinates.
Our instance has its own properties. Infographic: Olya Ezhak / Skillbox Media

An object's behavior is defined through methods—special blocks of code that can be called from various parts of the program. For example, a Character object might have methods such as movement, attack, defense, and interaction with the environment. Each of these methods determines how the object responds to events and interacts with other program elements, providing flexibility and control during development. This allows you to create more complex and dynamic scenarios in the gameplay or in any other program where objects are used.

  • walk,
  • attack,
  • talk,
  • pick up,
  • drop,
  • use.

Using these properties and methods can significantly speed up the development process and improve code readability. Programmers find it easier to write code when they use an object-oriented approach, which promotes more effective thinking and structuring of solutions.

Developers don't create universal functions for the program as a whole, but instead analyze the application, breaking it down into individual components. Each of these components is designed with its properties and behavior in mind, resulting in more structured and efficient code. This approach promotes a better understanding of the application's functionality and simplifies its future maintenance and development.

Many popular programming languages ​​use this paradigm. It allows developers to effectively organize and structure code, improving its readability and maintainability. Thanks to this paradigm, software development becomes more flexible and adaptive to changing requirements. Using this paradigm also facilitates easier error detection and elimination, which increases the overall reliability of programs. As a result, many developers choose this paradigm as the main one for creating their projects.

  • C#,
  • Java,
  • Python,
  • JavaScript,
  • PHP,
  • Kotlin,
  • Swift,
  • Objective-C,
  • C++.

We have an article about the principles of object-oriented programming (OOP) in Python. If you prefer Python to C#, you can get acquainted with the basic concepts of OOP in this language.

Pros and Cons of Object-Oriented Programming

Basic Principles of Object-Oriented Programming

Object-oriented programming (OOP) is based on four key concepts. These concepts form the foundation of the OOP paradigm and allow developers to create flexible and scalable code. The first concept is encapsulation, which provides the ability to hide the internal implementation details of objects, ensuring access to data only through certain methods. The second concept is inheritance, which allows you to create new classes based on existing ones, which promotes code reuse and simplifies its maintenance. The third concept is polymorphism, which allows you to use a single interface to work with different types of objects, which makes the code more versatile and adaptable. The fourth concept is abstraction, which allows you to focus on the key aspects of a system while hiding complex details. Mastering these four fundamental concepts is essential for successfully applying object-oriented programming to software development.

  • abstraction,
  • encapsulation,
  • inheritance,
  • polymorphism.

Consider the "Cat" class, which includes attributes such as "color," "breed," and "age," as well as methods such as "sleep." Having this class allows you to create an unlimited number of instances with different properties. For example, you could create several breeds of cats, each with unique characteristics such as color and age. This makes the class a convenient tool for modeling the diversity in the cat world and their behavior.

One class - different property values ​​Infographics: Olya Ezhak / Skillbox Media

Now let's look at the basic principles of object-oriented programming (OOP). OOP is based on several key concepts, such as encapsulation, inheritance, polymorphism, and abstraction. Encapsulation hides internal implementation details and exposes data only through methods. Inheritance allows new classes to be created based on existing ones, which allows for code reuse and simplifies maintenance. Polymorphism allows objects of different classes to respond to the same messages, increasing code flexibility. Abstraction helps focus on the core characteristics of an object, ignoring unimportant details. These principles are the foundation for creating structured, flexible, and maintainable code, making OOP an essential tool in software development.

When designing a class, it is important to focus only on the attributes and methods relevant to a specific application, excluding unnecessary details. For example, although all cats have hunting skills, if our program does not include functions for catching mice, there is no need to add this method to the class. This approach allows you to make the code more understandable and efficient, avoiding unnecessary complexity.

What else do domestic cats need? Infographics: Olya Ezhak / Skillbox Media

In our article, you will find detailed information about Abstraction and abstract classes in object-oriented programming (OOP). These concepts are key to understanding software design and code organization. Learn how abstraction helps hide complexity, and abstract classes provide universal interfaces for various objects. If you are interested in a deeper understanding of these topics, we recommend reading the corresponding article on our website.

Controlling access to an object's data is an important aspect of software development. This is necessary to prevent unauthorized changes and errors in the system. To ensure secure work with data, programmers create public methods that form the object's interface. These methods allow users to interact with data without compromising its integrity and protecting the object's internal logic. Proper use of interfaces helps avoid errors and improves code maintainability, which is an important factor in developing high-quality software.

Returning to the topic of our cats, we can allow the "age" attribute to change, but only upward, since cats do not get younger with time. The "breed" attribute should be left read-only, since an animal's breed remains unchanged throughout its life.

We can restrict access to certain properties ourselves. Infographics: Olya Ezhak / Skillbox Media

Encapsulation is a key concept in object-oriented programming, which involves hiding the internal implementation of an object and making its data accessible only through certain methods. This helps protect data from unauthorized access and modification. It is important to understand that encapsulation helps improve the structure of your code and its readability.

For example, in the Python programming language, encapsulation can be achieved using private and protected attributes. Private attributes are indicated by a double underscore before their name, making them inaccessible for direct access from outside the class.

Consider the following example:

«`python
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute

def deposit(self, amount):
if amount > 0:
self.__balance += amount

def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount

def get_balance(self):
return self.__balance # Method for accessing a private attribute
«`

In this example, the `BankAccount` class encapsulates the `__balance` property, providing methods for depositing and withdrawing funds, as well as a method for getting the current balance. This preserves data integrity and prevents it from being modified incorrectly.

For a more detailed study of encapsulation and its application in various programming languages, refer to the Skillbox Media guide.

Classes have the ability to pass their attributes and methods to descendant classes, which greatly simplifies the development process. Let's consider an example of creating a new class, "Domestic Cat," that inherits from the "Cat" class. This new class adds unique attributes, such as "owner" and "name," and introduces a new method, "beg for a treat." To implement this, simply declare "Domestic Cat" as a descendant of "Cat" and define the new attributes and methods. All other functionality is automatically inherited from the parent class, which makes development more efficient and structured.

Child classes inherit the properties and methods of their parent classes and also add new ones. Infographics: Olya Ezhak / Skillbox Media

Dive deeper into inheritance with code examples and helpful practical tips in "Inheritance and Polymorphism: Part 6 of the Object-Oriented Programming Guide." This material will help you better understand the concepts of inheritance and polymorphism and how they apply to software development.

This principle allows the same commands to be used for objects of different classes, even if their implementations differ. For example, we have a "Cat" class and a completely independent "Parrot" class, both of which have a "sleep" method. Even though cats and parrots sleep differently—a cat curls up in a ball, while a parrot sits on a perch—the same command can be used to perform these actions. This simplifies the code and makes it more versatile, which is especially important when developing complex software systems.

The method is the same, but the actions are different. Infographics: Olya Ezhak / Skillbox Media

Objects and Classes: How to Use Them

In C#, almost everything is a class, including strings, numbers, arrays, and other data types. Each class has its own properties, such as the number of characters in a string or the size of a data type, as well as methods that make working with objects easier. For example, methods can be used to sort arrays or perform arithmetic operations, such as adding numbers. Understanding classes and their capabilities is a key aspect of C# programming, allowing developers to create more efficient and organized applications.

Building on the base C# classes, it is possible to create your own classes. For example, you can use the Int64 data type to create floating-point number classes. Although such a class already exists in the standard library, we can override its functionality to suit our needs. This allows us to tailor the behavior of the class for specific tasks and improve its performance in our project.

When learning the C# programming language, developers are immersed in the concepts of classes and objects from the very first day. Classes are the foundation of object-oriented programming in C#, and objects are instances of these classes. For example, the first program most beginners write demonstrates creating a simple class and using it to create an object. This introduction to the basics of C# provides a better understanding of how the language works and lays the foundation for further exploration of more advanced topics such as inheritance, polymorphism, and encapsulation.

This code fragment creates a Program class, which includes a Main() method. This method is the entry point for program execution, making it a key element in the structure of C# applications. The Main() method is responsible for starting program execution and can accept arguments from the command line, allowing data to be passed when the application starts. Proper design and implementation of the Main() method are essential for the correct operation of the entire program.

In this example, the program interacts with the Console object by calling the WriteLine() method. This method prints the specified value to the console screen. Using the WriteLine() method allows developers to display text information, which is an important part of debugging and user interaction in C# applications.

The Console object includes various properties that allow developers to effectively manage console output. These properties provide access to functionality needed for debugging and monitoring applications. Using these properties, programmers can display messages, warnings, and errors, significantly facilitating the development and testing process. It is important to study each property of the Console object to optimize data output and improve code quality.

The absence of an object complicates the selection of background and font colors, as a program may have multiple variations of these parameters. Properly setting the color scheme is important for the visual perception and usability of the interface. Without a clear object for reference, determining preferred colors becomes difficult.

The program will output the following result:

Screenshot: Skillbox Media

How to create a class

To create To create a new class in Visual Studio, open the Project menu and select Add Class…. This will add a new class to your project, which is an important step in software development. Make sure you set up the namespace correctly and specify the necessary class parameters. After adding the class, you will be able to implement its functionality, which will improve the quality of your code and simplify its maintenance.

Screenshot: Skillbox Media

Enter the name and click the button «Add».

Screenshot: Skillbox Media

The program generates a separate file containing the following code:

Let's look at this in detail.

Namespace is a space namespace in which the class is located. This is an important tool for preventing class and variable name conflicts, especially when using third-party libraries. For example, you can create your own class called Console, and this will not cause errors, since it will be in a separate namespace. Using a namespace allows you to organize your code in a more structured way and makes it easier to maintain, improving readability and reducing the likelihood of errors related to duplicate names. Therefore, the correct use of namespaces is an important practice in software development.

The code uses the class keyword, which indicates the need to create a class with a given name. In this case, it is the Character class. Classes are the basis of object-oriented programming, allowing you to organize and structure your code, improving its readability and reusability. The Character class can include properties and methods that define the behavior and characteristics of an object, making it an important element in software development.

In programming, class names are usually capitalized, while object names should be written with a lowercase letter. This rule promotes better comprehension and makes code easier to read, which is important for developing and maintaining software solutions. Using the correct naming style helps developers quickly navigate the code and maintain its structure.

Everything enclosed in curly braces refers to the given class. Although the class does not contain methods or properties, an instance of it, that is, an object, can be created. This process is called declaring or instantiating the class. Creating an instance of a class allows you to work with objects that can have their own unique state and behavior.

To declare an object, you need to go to the main method and use the following code:

Creating objects in programming is similar to the process of declaring variables, but instead of a data type, the class name is used. The assignment sign is followed by the new keyword, followed by a constructor - a special method responsible for creating an object instance. Details on constructors and their role in object-oriented programming can be found in the section on methods.

How to Use Class Fields and Properties

Now you can add fields and properties to the class. Fields are declared in the same way as regular variables:

An object has its own fields, but they cannot be accessed from the outside due to access restrictions (details can be found in the article on encapsulation). To make fields accessible, you must use the public keyword before each field. Similarly, this keyword must be specified before the class definition.

Now you can return to the created object and access its health field. This allows you to effectively manage the object's state, which is especially important for game mechanics and applications where health plays a key role. Access to the health field allows you to make changes, track the current state and adapt the object's behavior depending on its vital signs.

Screenshot: Skillbox Media

With open access to the fields, it is possible to perform calculations and obtain their values. To restrict access to specific fields, it's recommended to use properties. This allows you to control access and protect important data in your code.

Special constructs called properties provide access to class fields. To create them, you must set the access level of the fields to private. This restriction allows them to be used only within the class itself, which promotes encapsulation and data protection. Using properties, developers can control access to fields, ensuring control over their reading and writing.

Currently, access to health information or object coordinates, as well as the ability to change them, is restricted. To restore this access, you must create the appropriate properties.

The access level is specified as public, followed by the property type and its name. Property names usually begin with a capital letter and must match the names of the fields. Two constructs can be used within a property:

  • get (getter - allows you to get the property value) - returns the value that comes after the return keyword;
  • set (setter - allows you to change the value) - specifies the field to be changed using the value.

The this keyword plays an important role in programming, indicating that a field belongs to a specific object. Although its use is not required, it significantly improves code readability, allowing developers to more easily understand the structure and logic of the program. Accessing this helps avoid potential errors and increases clarity when working with objects.

Such manipulations are necessary to ensure access control to fields, which allows the developer to control their use. For example, you can create a property whose value will change depending on the fulfillment of a certain condition. This allows for flexible configuration of the application's logic and enhances its security by preventing unauthorized access to internal data.

The value returned by the system depends on the character's health. If the character's health is below zero, false is returned. Otherwise, when health is above zero, true is returned. This condition allows for efficient tracking of the character's state in the game and management of their actions.

The program operates as follows: it performs specified functions, processing data and providing results. The user enters the required parameters, after which the system analyzes the information. Based on the received data, the program generates results that can be presented in various formats. This allows for streamlining workflows and increasing task efficiency. Thanks to the intuitive interface, users can easily navigate the functionality of the program and quickly get the desired results.

The following will be displayed on the screen:

Screenshot: Skillbox Media

How to create Method

Now we can move on to studying the behavior of objects. This is implemented through methods—specialized blocks of code that help eliminate duplication in a project and optimize its structure. Methods allow you to effectively manage the functionality of objects, simplifying the development process and improving code readability. Using methods, you can create more flexible and maintainable applications.

Methods in programming are analogous to functions and procedures, but they have an important difference: methods are always bound to a specific class. For example, within the Character class, you can implement the Move() method, which will control the character's movement. This allows you to organize your code in a more structured way and encapsulate the logic associated with a specific object. Methods, like functions, can return values ​​or perform actions without returning a result, which makes them a universal tool for interacting with objects in object-oriented programming.

The access level is specified as public, followed by the return type. In this case, void is used, which informs the compiler that the method does not return any values. Next comes the method name, enclosed in parentheses.

The method accepts arguments in parentheses that determine the direction of movement. The result of the method depends on the arguments passed. Correctly choosing the arguments is critical to achieving the desired result.

Example of using the method:

The user displays their coordinates and enters the direction of movement, while the character moves using the Move() method. This process continues until the exit command is entered.

Screenshot: Skillbox Media

If you want the method to return a value, you must specify its type and use the return statement. This allows you to not only determine the data type that will be returned but also ensure that the result is processed correctly in the future. Make sure that the return value matches the specified type to avoid runtime errors. Proper use of the return statement in methods improves the structure of your code and makes it easier to read and maintain.

This method takes a Character object as an argument and compares its coordinates with the specified ones. If the coordinates match, the method returns true; otherwise, it returns false. This approach allows you to efficiently check the character's position in the game space, which can be useful for implementing various game mechanics, such as collisions or interactions between objects.

Using this approach can be quite effective. It allows you to optimize processes and improve results. For example, you can apply it to improve productivity, enhance customer service, or increase sales. It is important to consider the specific features of your industry and adapt the methodology to your needs. This approach will not only improve current metrics but also create a sustainable foundation for further growth.

The presented program compares the coordinates of two objects and displays the result. Since the objects have identical fields, they will be considered equal. This allows you to effectively manage data and conduct analysis using object-oriented programming.

Screenshot: Skillbox Media

Object constructor

In the given example, the object is created with a pre-defined However, it is possible to specify your own parameters. For this purpose, constructors are used—special methods that are called when a class instance is created. Using constructors, you can pass the required parameters to an object and perform the desired operations, making them an important tool when working with object-oriented programming. Using constructors allows for flexible configuration of objects and improves their functionality.

This text presents an example of a class that includes a constructor. A constructor in a class allows you to initialize an object with specified parameters. It plays an important role in object-oriented programming, ensuring that class instances are created with the required values. Using a constructor simplifies the creation and configuration of objects, and also makes the code more readable and structured.

An example implementation of a class with a constructor allows you to see how you can create objects and manage their properties. This approach provides flexibility in software development, allowing you to easily modify and extend the functionality of classes. Proper use of constructors is key to creating high-quality and maintainable code.

In programming, a constructor is a method that doesn't require a return type, as it automatically returns the object it creates. To declare a class instance, simply call the constructor with the required number of arguments. This simplifies the process of creating objects and makes the code more concise and understandable.

The program will produce the following result:

Screenshot: Skillbox Media

Homework

Create A console game in which the player controls a character using text commands. The game must implement the following features: the ability to move the character around the game world, interact with objects and NPCs, and a combat and quest system. The player must be able to explore various locations, collect items, and develop the character's skills. The main goal of the game is to complete tasks and achieve certain results, which will ensure an exciting gameplay.

  • movement;
  • attack;
  • gaining experience for defeating enemies;
  • increasing the level and health of the character.