Computer Science

Encapsulation programming

Encapsulation programming is a fundamental concept in object-oriented programming that involves bundling data and methods that operate on that data within a single unit. This unit is known as a class, and it provides a way to hide the implementation details of the class from other parts of the program. Encapsulation helps to improve the security, maintainability, and flexibility of software systems.

Written by Perlego with AI-assistance

7 Key excerpts on "Encapsulation programming"

  • Extreme C
    eBook - ePub

    Extreme C

    Taking you to the limit in Concurrency, OOP, and the most advanced capabilities of C

    C cannot be object-oriented because it is located on the barrier between object orientation and procedural programming. Object orientation is the human understanding of a problem and procedural execution is what a CPU can do. Therefore, we need something to be in this position and make this barrier. Otherwise high-level programs, which are usually written in an object-oriented way, cannot be translated directly into procedural instructions to be fed into the CPU.
    If you look at high-level programming languages like Java, JavaScript, Python, Ruby, and so on, they have a component or layer within their architecture which bridges between their environment and the actual C library found inside the operating system (the Standard C Library in Unix-like systems and Win32 API in Windows systems). For instance, Java Virtual Machine (JVM ) does that in a Java platform. While not all these environments are necessarily object-oriented (for example JavaScript or Python can be both procedural and object-oriented), they need this layer to translate their high-level logic to low-level procedural instructions.

    Encapsulation

    In the previous sections, we saw that each object has a set of attributes and a set of functionalities attached to it. Here, we are going to talk about putting those attributes and functionalities into an entity called an object. We do this through a process called encapsulation .
    Encapsulation simply means putting related things together into a capsule that represents an object. It happens first in your mind, and then it should be transferred to the code. The moment that you feel an object needs to have some attributes and functionalities, you are doing encapsulation in your mind; that encapsulation then needs to be transferred to the code level.
    It is crucial to be able to encapsulate things in a programming language, otherwise keeping related variables together becomes an untenable struggle (we mentioned using naming conventions to accomplish this).
    An object is made from a set of attributes and a set of functionalities. Both of these should be encapsulated into the object capsule. Let's first talk about attribute encapsulation
  • IT Interview Guide for Freshers
    eBook - ePub

    IT Interview Guide for Freshers

    Crack your IT interview with confidence

    Encapsulation: Data encapsulation is a key OO concept that facilitates binding code and data in a single translation unit called a class and hiding the implementation details from outside world. This prevents un-warranted access to data members and restricts the enduser to leverage the public methods of the class. Encapsulation implements one of the four fundamental OOP concepts, that is, data hiding. An object binds together the properties and methods that manipulate the data, which is safe from outside manipulations. Encapsulation is usually the process of hiding the elements from the outside world of an object that do not contribute to its key features.
  • Abstraction: Abstraction is the mechanism of hiding unwanted details of an object from the outside world, and exposing just relevant details. The best example of abstraction is the interface. Encapsulation hides the unimportant details of an object from the outside world and abstraction makes just the relevant information of an object available to the outside world.
  • The following table compares abstraction and encapsulation:
    Figure 6.7: Abstraction vs Encapsulation

    Composition and inheritance

    What are the types of inheritance?

    Inheritance is an OO feature of a class to leverage the properties and methods of another class while adding its own features. It enables you to add fresh features and functionalities to an existing class without changing the existing class. There are four types of inheritance in OOPs:
    • Single inheritance: This mechanism consists of one derived class and one base class. The following diagram depicts a single inheritance:
      Figure 6.8: Single inheritance
    • Hierarchical inheritance: This mechanism consists of one base class and multiple derived classes from this base class.
    • Multi-level inheritance: This mechanism consists of a class derived from a derived class.
    • Multiple-inheritance:
  • Programming in C#: Exam 70-483 (MCSD) Guide
    eBook - ePub

    Programming in C#: Exam 70-483 (MCSD) Guide

    Learn basic to advanced concepts of C#, including C# 8, to pass Microsoft MCSD 70-483 exam

    • Simaranjit Singh Bhalla, SrinivasMadhav Gorthi(Authors)
    • 2019(Publication Date)
    • Packt Publishing
      (Publisher)
    Encapsulation basically involves grouping all the related properties and methods that access them in an object. Whenever an application is being designed, we need to decide how many objects should be defined in it, along with the associated attributes and methods available in it.
    For instance, in the car example, we have the following associated attributes and methods:
    • car is an object.
    • The make, model, and color are the different attributes that are present in the object.
    • start, stop, and accelerate are the different methods that are present in the object.
    Encapsulation allows us to achieve the following functionality in any application:
    • Security : Using encapsulation, we can define our attributes in such a way that not all of the attributes of an object are exposed to the entire application. In Chapter 2 , Understanding Classes, Structures, and Interfaces, we used access modifiers to control the security access of any property/method in the class/in the namespace/in the assembly, as well as in the entire application.
    • Code maintenance : From a maintenance perspective of a function, it's always desirable that the function has as few attributes as possible.
    Using encapsulation, we can organize the required parameters of a function as an attribute of the class and thus we are not passing them explicitly in every call. In the following code example, we will go through a code sample in C# and understand how this can be achieved. Passage contains an image

    Code example

    Let's consider an example of a banking application. In this banking application, we need to implement a scenario related to opening an account.
    From a class implementation perspective, the following are the possible attributes that should be in the Account class. Please also note that there will be an additional class, Customer, to signify the person who is opening the account:
  • Beginning Java Programming
    eBook - ePub

    Beginning Java Programming

    The Object-Oriented Approach

    • Bart Baesens, Aimee Backiel, Seppe vanden Broucke(Authors)
    • 2015(Publication Date)
    • Wrox
      (Publisher)
    One of the greatest sources of errors in programs is when some parts of the program are interfering with other parts. Indeed, it is easy to see that, in this course administration example, the addition of more procedures and data will quickly lead to so-called spaghetti code, where it becomes very complex to follow the trace of execution as data can jump from one part to another in the program. Object-oriented programming resolves this issue by encapsulating both data and behavior within an object. However, this in itself is not sufficient to guarantee maintainable programs, as you also need to prevent an object’s data from being directly accessible by other objects. Therefore, object-oriented programming also emphasizes the concept of information hiding, where an object’s data can by default be accessed only by methods contained in the same object. When data elements of one object need to be used by another object, the latter must call a publicly accessible method of the former, basically requesting the “owning object” to perform a change to its data. As such, object-oriented programming encourages programmers to place data where it is not directly accessible or modifiable by the rest of the system. Instead, the data is accessible through methods, which can also include checks and safeguards to make sure the requested change is permitted by the owning object. Object-oriented programming also defines concepts to help with structuring programs so that they can be easily extended and evolved. These concepts are polymorphism, which is the ability to treat objects of different types in a similar manner, and inheritance, which is a concept to allow for extending objects and enabling code reuse. You will revisit these concepts in more detail in Chapter 8, when you delve deeper into object-oriented concepts
  • Anyone Can Code
    eBook - ePub

    Anyone Can Code

    The Art and Science of Logical Creativity

    3 But most modern applications have two important features:
     
    3 Linus Torvalds, the creator of Linux Operating System, I quoted to say “limiting your project to C means that people don’t screw things up with any idiotic ‘object model’.”
    • They have different data items that can be grouped into separate entities with their own operations.
    • They have a non-linear behavior that consists of entities interacting with each other at non-pre-defined times instead of a predefined flow of actions.
    Organizing programs as a series of potentially interactive entities, each capable of performing operations, is the key advantage of OOP , which is made possible by encapsulation, the first property of Object-Oriented languages. Encapsulation provides multiple benefits to programmers:
    • More manageable programs as the related code and data are clearly grouped
    • More reusable programs as the modules are more self-sufficient and easier to copy to another application (source code or compiled binary)
    • Information hiding is better supported through defining objects and their interfaces4
    • Interactive applications are easier to design with Object-Oriented Programs compared to procedure-oriented ones.
    I will discuss and illustrate these advantages in this and the next section. OOP has two other basic properties called Inheritance and Polymorphism that I will introduce in Part 5.
    The starting point of any object-oriented program, which is the key to creating a manageable and reusable code, is to select and define the right classes. Recall the data-centered approach for designing programs that I introduced earlier in the book:
  • Expert C++
    eBook - ePub

    Expert C++

    Become a proficient programmer by learning coding best practices with C++17 and C++20's latest features

    • Vardan Grigoryan, Shunguang Wu(Authors)
    • 2020(Publication Date)
    • Packt Publishing
      (Publisher)
    All of them are defined in the <compare> header. The compiler generates operators based on the return type of the three-way operator. Passage contains an image

    Encapsulation and the public interface

    Encapsulation is a key concept in object-oriented programming. It allows us to hide the implementation details of objects from the client code. Take, for example, a computer keyboard; it has keys for letters, numbers, and symbols, each of which acts if we press on them. Its usage is simple and intuitive, and it hides a lot of low-level details that only a person familiar with electronics would be able to handle. Imagine a keyboard without keys— one that has a bare board with unlabeled pins. You would have to guess which one to press to achieve the desired key combination or text input. Now, imagine a keyboard without pins— you have to send proper signals to the corresponding sockets to get the key pressed event of a particular symbol. Users could be confused by the absence of labels and they also could use it incorrectly by pressing or sending signals to invalid sockets. The keyboard as we know it solves this issue by encapsulating the implementation details – th e same way programmers encapsulate objects so that they don't load the user with redundant members and to make sure users won't use the object in the wrong way.
    Visibility modifiers serve that purpose in the class by allowing us to define the accessibility level of any member. The private modifier prohibits any use of the private member from the client code. This allows us to control the modification of the private member by providing corresponding member functions. A mutator function, familiar to many as a setter function, modifies the value of a private member after testing the value against specified rules for that particular class. An example of this can be seen in the following code:
  • Hands-On Design Patterns with Java
    eBook - ePub

    Hands-On Design Patterns with Java

    Learn design patterns that enable the building of large-scale software architectures

    Objects are at the core of OOP. This principle aims to remind software designers and developers to isolate objects to a specific model. Using our Bicycle class as an example, we would create Bicycle objects that contained the appropriate attributes and behaviors. The bicycle attributes used in this chapter were gears, cost, weight, and color. We created accessors and mutators for each of those attributes. We also created a method that echoed the object's attributes to the output console. No behaviors were added to the Bicycle object, but we could have included behaviors such as upgrade().
    What we did not include in the Bicycle class were attributes and behaviors that were ancillary to the Bicycle object. Examples of these include the owner's address, vacation details, and more. While the data might be somewhat related to a specific Bicycle, it is not part of a real-world bicycle that we need to model.
    Adhering to this principle helps ensure our code is concise, easy to maintain, and portable. Passage contains an image

    Encapsulating to protect

    Earlier in this chapter, we defined encapsulation as the hidden nature of an object's data. Granting access to an object's data via its own accessors and mutators is a great approach to data protection.
    We use encapsulation as an approach to data protection in OOP. Encapsulating too much data into a class is an anti-pattern—something that should be avoided. As with the create concise objects approach, we should identify what data all copies of an object have in common and only encapsulate those data elements. Other data might be better suited for an ancillary class.
    Passage contains an image

    Being purposeful with inheritance

    Inheritance is a powerful OOP construct. We can model objects efficiently, as was illustrated with the bicycle. We know that the following relationships exist:
  • Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.