Encapsulation

KS3 Computer Science

11-14 Years Old

48 modules covering EVERY Computer Science topic needed for KS3 level.

GCSE Computer Science

14-16 Years Old

45 modules covering EVERY Computer Science topic needed for GCSE level.

A-Level Computer Science

16-18 Years Old

66 modules covering EVERY Computer Science topic needed for A-Level.

GCSE Programming Resources (14-16 years)

  • An editable PowerPoint lesson presentation
  • Editable revision handouts
  • A glossary which covers the key terminologies of the module
  • Topic mindmaps for visualising the key concepts
  • Printable flashcards to help students engage active recall and confidence-based repetition
  • A quiz with accompanying answer key to test knowledge and understanding of the module

A-Level Problem solving and programming (16-18 years)

  • An editable PowerPoint lesson presentation
  • Editable revision handouts
  • A glossary which covers the key terminologies of the module
  • Topic mindmaps for visualising the key concepts
  • Printable flashcards to help students engage active recall and confidence-based repetition
  • A quiz with accompanying answer key to test knowledge and understanding of the module

What is Encapsulation

One of the basics of OOP is encapsulation. This applies to the packaging of information with the tools that function on the information. Encapsulation is worn to mask the values or status of a standardised data thing within a folder, avoiding straight entry to them by unauthorised gathering.

The idea of encapsulation applies in object oriented programming languages to the bundling of facts into a one structure, through with the procedure that acts on that figure. In the context of classes, most of the programming tongues use encapsulation often. A class is a programme or code figure that authorises fabricators to construct an object that has behaviours (functions or methods) and variables (data). A class is an example of encapsulation in that it consists of data packed into a single unit and methods.

 Encapsulation can also mention a process by which straight entry to some elements of an item is limited, so that customers are powerless to enter state values for all changeable items of a given item.       

Definition of Encapsulation

Encapsulation is characterised as wrapping up one unit of data. It is the structure that connects the programme and the information it controls. Another method to believe of encapsulation is a defensive barrier that stops the code behind this barrier from accessing the data.

  1.  The facts of a class are shielded from any more class functionally in encapsulation and can only be entered by any organ method of their own class in which they are announced.
  2. In encapsulation, the facts in a class is shielded from more classes using the concept of facts shielding that is done by rendering the organ or class procedure secret and the class is revealed to the end user or the environment without giving any information in back of execution using the idea of abstraction, it is also regarded as a mixture of abstraction and code beating.
  3.  Encapsulation can be done by: marking all the instance changeable as personal and writing common procedures in the instance to put and receive the variable worth
  4. Encapsulation mentions the throw of facts with the procedures that work on that facts in object-oriented programming (OOP), or the limiting of straight entry to certain components of an object. Encapsulation is worn to mask the worth or ranking of a standardised data object within a folder, avoiding straight entry to them by uncertified parties. 

In Java to accomplish encapsulation

  •  Declare a class’s variables as personal.
  • Common mechanisms for public setters /getters to alteration and interpret the values of fluid.

Example of Encapsulation

Here is an example which describes the encapsulation in details.

class Encapsulation {

    private int employeeNum;

    private String employeeName;

    private int employeeAge;

 // getter and setter

    public int getEmployeeNum () {

        return employeeNumber;

            }

 public String getEmployeeName () {

        return employeeName;

            }

 public int getEmployeeAge () {

        return employeeAge;

            }

 public void setEmployeeAge (int newValue) {

        employeeAge = newValue;

            }

public void setEmployeeName (String newValue) {

        employeeName = newValue;

            }

 public void setEmployeeNum (int newValue) {

        employeeNum = newValue;

            }

}

public class Encaps {

            public static void main (String args []) {

         Encapsulation abc = new Encapsulation ();

         abc. setEmployeeName (“Asif Ali”);

         abc. setEmployeeAge (99);

        abc. setEmployeeNum (2233);

         System.out.printIn(“Employee Name: ” + abc. getEmployeeName ());

         System.out.printIn(“Employee Num: ” + abc. getEmployeeNum ());

         System.out.printIn(“Employee Age: ” + abc. getEmployeeAge ());

            }

}

Output for the above program is:

Employee Name: Asif Ali

Employee Num: 2233

Employee Age: 99

Advantage and Disadvantage of Encapsulation:

Advantage:

  • Data Hiding:

The consumer would have no plan about the class ‘s internal execution. How the class stores values in the variables would not be accessible to the user. He only realises that we transfer the worth to a compositor process, and with that value, fluid gets initialized.

  • Increased Flexibility:

We can make the factors of the class as perused just or compose just relying upon our prerequisite. On the off chance that we wish to make the factors as perused just, at that point we need to exclude the setter strategies like setEmployeeName (), setEmployeeAge () and so on from the above programme or on the off chance that we wish to make the factors as compose just, at that point we need to overlook the get techniques like getEmployeeName (), getEmployeeAge () and so forth. From the above programme.

  • Reusability:

Encapsulation also increases the recyclability of current specifications and is simple to modify.

  • Testing code is easy:

For component testing, the encapsulated code is easy to analyse.              

Disadvantage:

  • The negatives are the inefficiency, as you pointed out, of the extra indirection and the fact that it is not implemented by the compiler. To kill the advantages, all it takes is the worst programmer using one unencapsulated guide.
  • Also, replacing it with a non-null default value with exactly the same characteristics is not the best way to address a null pointer problem. The issue with null pointer dereferences is not that a default is caused by them. That’s a symptom just. The issue is that an unwanted default / uninitialized value could not always be treated by the programmer. For your self-encapsulation pattern, the issue still must be addressed separately.
  • The proper way to overcome a null pointer problem is not to construct an object until it is possible to add a semantically true non-null value into the attribute and delete the object until setting any of its attributes to null is necessary. There is never a need to verify it since there is never a chance for a pointer to be empty. 

Types of Encapsulation

There are three types of Encapsulation.

  • Member Variable Encapsulation
  •  Function Encapsulation
  • Class Encapsulation

Member Variable Encapsulation

Both data organs should be announced as personal Class organs in Object Oriented Programming. An object that wants to change or retrieve a data member ‘s value can use the Setters or Getters functions. This is most commonly known to you as Data Participant Encapsulation. However, encapsulation of the data organ is not the only method to encapsulate data. Functions and sections can be encapsulated, too.   

Function Encapsulation

Functions used only with the API ‘s internal deployment must always be deemed Confidential. The following classification, for instance, describes a circle. We have a setter method that modifies a circle ‘s diameter. It is clear that, because the consumer can have this info, this approach should be made public. The Calculate Circumference) (method should not, however, be deemed to be available. This method should not be accessed by the user, and it should be declared as a private system. Mind, conceal any feature that does not have to be common at all.     

Class Encapsulation

For classes used with the API ‘s internal implementations, the same logic holds. Such classes do not be part of any API ‘s public gui. You should conceal them from your users and remain them personally. For instance, your API can have a class that, based on its location, sets a specific gradient colour to a circle. To sum up, Object Programming offers three separate ways of encapsulating knowledge. Data participants, processes, and groups may be encapsulated. Hope that’s been effective.

Benefits of Encapsulation:

  1. Read-only or write-only fields of a class may be generated.
  2.  A class should be in full possession of what is contained in its fields.

How is Information Hidden via Encapsulation?

Encapsulation helps developers to package data and methods together, as we discussed earlier, but it can also be used to cover confidential data that should not be accessible to users. Information hiding is managed in the Java programming language, as in many other languages, using getter / setter methods for data attributes that are readable or that can be modified by other classes.

A getter approach is used to extract the value of a particular variable within a class. For setting or changing the value of a particular variable within a class, a setter method is used. Programmers may use access modifiers, along with the data and methods they provide, to describe the visibility and functionality of classes.

You may utilise the encapsulation principle to enforce an information-hiding process, as explained at the outset. This is one of the most broadly used procedures in Java, analogous to the distraction principle. In nearly all well-implemented Java classes, you can find instances of it. By making the class assign unavailable from the surface and by supplying getter and/or setter procedures for assign that must be legible or modified by other classes, you implement this knowledge hiding function.      

Access Modifiers in Encapsulation:

Four permission accessories that you can use to specify the appearance of classes, procedures, and features are provided by Java. They each define a particular accessibility level, and you can use only one accessory per class, function, or feature. You should still use the most stringent modifier as a rule of thumb that also helps you to enforce your occupation argumentation.

Starting from the most stringent to the least, these modifiers are:

  • public
  • private
  • protected
  • no modifier

Public:

This is the modifier with the least restrictive entry. Within your stream class and all other classes, the procedures and features that use the common modifier can be obtained. Common procedures and features are part of your class’s common API and of any feature of which you use them. It is almost never a smart idea on any attribute, and before you employ this modifier on a tool, you should think twice.

 When a process is publicly usable, you need to be sure that it is properly defined and that all input values are treated robustly. Bear in mind, however, that any component of the proposal will use this strategy sooner or later, making it impossible to alter or delete it.

Another value of the multiple access modifiers is demonstrated by the brewCoffee process. Not only can you use it to mask records, but it can also be used to help distraction. The control modifiers guarantee that only the abstraction provided by the brewCoffee system can be named by an external class, but not the internal methods.

Private:

This is the control parameter that is the most stringent and most widely used. If you use a personal accessory for a feature or procedure, only inside the same class can it be accessed. This feature or method will not be reached by subclasses or all other classes within the same or a separate set.

As a rule of thumb, for all features and inner procedures that should not be named from outer classes, the private modifier should be the default option. When you are using inheritance, you may need to make an exception to this rule, and several of the subclasses require direct access to a feature or interior procedure. You should use the safe accessory rather than the personal one in that situation.

Protected:

You may access attributes and methods protected by the entry accessory within your class, all classes within the same bundle and all subclasses within the same or other bundles. The safe modifier is often used for interior procedures that subclasses need to call or bypass. You may also use it to allow subclasses to straight entry access a superclass ‘s interior features.

 In other sense Code within the same unit, all classes in the same offer, and all subclasses in the same or other offer may be accessed by an element or method that is covered.     

no modifier:

You can use it from your class and from all classes within the same offer although you do not have any use variable for your attribute or process. That’s why package-private is sometimes referred to. It is only within the CoffeeMachine class that certain attributes and methods can be included and are not part of the public API.

In the beginning, it may sound a little complicated, but it’s really handy when a well-defined collection of logic is applied by the classes in your package, and you desire to manage the API that is open to classes outer this offer. To enforce a system that can only be used by classes within this module, you can then use programme visibility. This helps you to generate an interior and an outer API for the package.

Hiding data concerning characteristics and methods using encapsulation has many advantages. One is that it stops scripts or APIs that use the code from being written by other developers. Users of a class don’t understand how a class holds the data with encapsulation, and the developer will modify a field’s data form without requiring developers and class users to alter their code.

Accessibility matrix in Encapsulation

A description of the multiple control accessory and the usability of the features or procedures can be found here.

ModifierClassPackageSubclassOther Classes
PublicyesNoNoNo
PrivateyesYesNoNo
ProtectedyesYesYesNo
No ModifieryesYesYesYes

Assistance to combat cyber threats by encapsulation and sumo logic

As a means to secure confidential data and ensure compliance with industry-specific data protection and privacy standards such as HIPAA and PCI DSS, IT companies may enforce encapsulation. The encapsulation mechanism allows compartmentalising data, reducing bugs and supplying consumers solely on a need-to-know basis with details on code implementations. With cutting-edge vulnerability identification and security analytics powered by artificial intelligence, Sumo Logic complements the latest cybersecurity assessment.

Encapsulation and Containerization Explained

Containers are a relatively modern form of software that, along with all of its libraries and other dependencies it requires to run, can be used to basically bundle a piece of code. Containers build an encapsulated simulated world where the least amount of disc space and processing capacity can be used to run a programme. A community of containers can share access to a single operating system and rely on a single piece of hardware for their computing power.

Because of its highly effective use of computational power, containerization has arisen as an alternative to virtual machines. Virtualization has made it easier to run multiple operating systems and programmes at the same time by sharing a single computer’s resources. By sharing a server operating system and loading the container runtime engine onto the operating system of the host computer, containers improved on this concept.

For each instance of the operating system it operates, a computer running four virtual machines expends extra energy, while a computer with a containerization engine installed might run the same number of applications on a single operating system. As a result, using the same processing power as a single virtual machine, multiple containers can run.

Containers are also one instance of encapsulation, where data and strategies are merged into a single container.      

Difference Between Inheritance, Encapsulation and Abstraction

Along with inheritance, the three key concepts of object-oriented programming are encapsulation and abstraction. Inheritance is a process that causes one class to absorb the characteristics of another class, in the same manner as each of their parents inherits those traits from an infant. Inheritance encourages programmers to build a new class that reuses a current class ‘s data members and methods.

In order to minimise ambiguity and help users communicate more easily with a programme, abstraction happens when a programmer masks all unnecessary details about an object or an instantiated class. The word abstraction can be used to define the way any of the knowledge stored in an entity or class is hidden, but it can also apply to the entity itself. An abstraction is any called object containing a collection of data and actions that are unique to the original object ‘s individual use.

Grady Booch writes this in the popular programming text Object-Oriented Research and Design:

 “Abstraction and encapsulation are additional concepts: abstraction focuses on an object’s measurable actions. Encapsulation focuses on the implementation that produces this conduct”

An abstraction refers to how an object and its actions are represented to the user, described differently, and encapsulation is a technique that helps to build the interface. Dream of your cell phone ‘s gui. You don’t deal explicitly with the code that helps your handset to connect to the internet, send a text message or play a video game, whether you’re using an Android operating system or iOS. Instead, with a user interface that is designed to streamline your workflow and make it easy to navigate the tools and methods you need to accomplish a job, you connect with the file. The interface is abstracted from the real execution of the code in this scenario.       

Summary:

  • n oop, encapsulation is one of the main principles. It defines the bundling into one unit of data and methods working on this data. The introduction of an information-hiding device is also used. In order to monitor and limit external access to these attributes, this process restricts the availability of features to the current class and uses common getter and setter procedures.
  • We might assume that the object “knows how” to do stuff with its own information, and it’s a bad idea for us to enter its internal data and do stuff ourselves with the data. We can implement a new method or change an existing one if an object does not have an interface method that does what we want to do.
  • Some languages have features which allow us to strictly implement encapsulation. We may specify access permissions on object attributes in Java or C++ and make it illegal for them to be accessed from outside the methods of the object. Writing setters and getters for all attributes is often called common practise in Java, particularly though the getter merely retrieves the attribute and the setter just assigns it the value of the parameter that you move in.
  • In Python, the language does not implement encapsulation, but there is a convention that we may use to signify that a property is meant to be private and is not part of the public interface of the object: we start with an underscore in its name. The use of a property decorator to substitute a basic attribute with a parameter without modifying the interface of the object is also provided by Python.      

References:

  1. Boyapati, C., Liskov, B., & Shrira, L. (2003). Ownership types for object encapsulation. ACM SIGPLAN Notices, 38(1), 213-223.
  2. Fukushima, K., Tabata, T., & Sakurai, K. (2003). Proposal and evaluation of obfuscation scheme for Java source codes by partial destruction of encapsulation. In Proc. of International Symposium on Information Science and Electrical Engineering (pp. 389-392).
  3. Roth, A. (2005, June). Specification and verification of encapsulation in Java programs. In International Conference on Formal Methods for Open Object-Based Distributed Systems (pp. 195-210). Springer, Berlin, Heidelberg.
  4. https://www.geeksforgeeks.org/encapsulation-in-java/#:~:text=Encapsulation%20is%20defined%20as%20the,the%20code%20outside%20this%20shield
  5. https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)
  6. https://www.tutorialspoint.com/java/java_encapsulation.htm
  7. https://stackify.com/oop-concept-for-beginners-what-is-encapsulation/
  8. https://www.sumologic.com/glossary/encapsulation/
  9. https://press.rebus.community/programmingfundamentals/chapter/encapsulation/
  10. https://www.haroldserrano.com/blog/the-tree-types-of-encapsulation-in-object-oriented-programming