Question

Interviewer: What is encapsulation and how do you achieve it in Java?

Me: Encapsulation is a mechanism to hide information from the client. The information may be data or implementation or algorithm. We achieve this using access modifiers.

Interviewer: This is data hiding. How do we achieve encapsulation in Java?

Me: uummmm

Concrete Question: Other than 'Access Modifiers', what is the way to implement Encapsulation in Java?

Was it helpful?

Solution

More generally encapsulation refers simply to bundling the data (e.g. of an object) with the operations on that data. So you have a class encapsulating data - fields - along with the methods for manipulating that data.

But encapsulation is also sometimes used in the same way as your answer, and indeed, one of the points of bundling data and methods is to hide the implementation.

I suppose a better answer than just use methods and make all fields private is: use interfaces. This way, operations on an object are purely based on the interface contract, and are in no way tied to the fields or helper methods used to implement that contract internally.

OTHER TIPS

Encapsulation

In general Encapsulation means to bundle similar items, simple as that.

For example, take a Student class where we will have students instance variables and behaviors/methods acting on those instance variables @ one place.

Why it is important? We don't want our code scattered all around in our code Base.

If let say we need to make changes then we need find the variants(of that changes) at all the places. By Bundling similar items we are just avoiding such scenarios and it also helps to make our Bundled code more focused.

Data Hiding

It just provides a way to protect your data from the outside world. What it means is, lets say if I made my instance variable public, then anyone can change its state. But if we make our instance variable private/protected then actually we are restricting outside entities from making changes to it.

Comparison/Discussion

Now question arises, in what respect are we making our variables protected?

Again we need to understand that Encapsulation is just the container we need to place our similar items.

Its just act like a Black box to outside world. Outside world (I mean to say clients/consumers: using our Student class) don't know the internal details/implementation details of the Student class and actually they should not care about the internal details/implementation details of the class. They just want some methods/APIs so that they can use them in their client application.

So my point is all student related behaviors/variables are placed in a Black box which we are calling it as a class. Now its up to designer of the class what are the elements of the class should be hidden and what should not be hidden from outside world.

Now coming back to the question In Java: we are making our variables private it means they are class protected.If we want our instance variables to be accessible throughout the package then they are package protected. Through out project they are public. So what I mean to say is to hide data you need some sort of container where you will put your data and hide with respect to container.

So what I feel Data Hiding is not possible without Encapsulation. You can't hide your data without putting it in some form of container. Again I'm reminding you that I'm putting this on the Object Oriented Language context.

But yes Encapsulation is possible without hiding your data. Put all things public and you can the see the affect.

Encapsulation: Take the example of a capsule. If you open it, it contains a lot of ingredients in it. Object Oriented programming's Encapsulation is also like that. As the name suggests "Encapsulation means to encapsulate (make a capsule of) all the data members, attributes and corresponding methods within one single capsule.

How do you do it: Lets say you made a class named "Car". Now car has a color price and model. These are attributes, and it has a run method. So here you've encapsulated all these attributes and methods of a vehicle named "Car". When you create an instance of car like so

Car myCar = new Car();

You can access all the attributes of Car using the myCar variable.

"Data hiding": Data hiding is controlled in Java using access modifiers. To access the data members you use ACCESSORS while to modify the data you use "Mutators". Java doesn't provide accessors and mutators by itself, you create them yourself (getters and setters). While C# provides PROPERTIES to do so.

I hate to do this but, from Wikipedia:

In programming languages, encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination thereof:

  1. A language mechanism for restricting access to some of the object's components.
  2. A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data

Your explanation was more along the lines of the first notion, the interviewer was looking for something on the second.

Data encapsulation refers to the mechanism of keeping all the related properties and method into a single entity.

Example: A Car. It keeps steering wheels, tires, engine and all the related stuffs into one collective entity known as Car.

In programming languages the encapsulation is achieved with classes. A class contains all the properties and related methods in one single entity that is designed to do a specific task.


Data hiding refers to hiding the unimportant details from the user and show him only the relevant data.

Example: When we press brakes or accelerator in a car, we don't know what's happening behind the scene (how its increases its speed or how its applying the brakes into tires). All we know is that we have brake and accelerator to perform the desired outcome.

In programming this is done with the help of access modifiers. Private members are not accessible from outside the class and only public members are accessible to users. The private members can only be accessed from members of the class thus providing the security for private members to be directly evaluated from the outside of the class.

Data hiding means we are providing security to data within the class.

Abstraction means hiding the code by defining member functions.

Encapsulation is the combination of abstraction and data hiding, means we are wrapping data and code associated with that data. For ex bean class

    class student {
private int age;  // Data Hiding 
public setAge(){} // Abstraction 
public getAge(){} // Abstraction 
}

student class is encapsulated.

encapsulation = data hiding + abstraction

The question appears misleading, I doubt that anybody but the interviewer could possibly answer it and chances are that his/her answer could be wrong. Most importantly, it is not clear what the question is supposed to evaluate or discover.

Still, I gave it some thought and the following is what I believe could be my attempt to answer the question.

With Access Modifiers

In Java, encapsulation is implemented by hiding details using the accessibility modifiers (i.e. public, protected, private, etc.). With these levels of accessibility you control the level of information hiding. The less restrictive the level, the more expensive change is when it happens and the more coupled the class is with other dependent classes (i.e. user classes, subclasses).

Evidently, encapsulation is more than just hiding state. In Java you can hide entire classes and interfaces and their state and behaviors, by this, hiding the implementation details of an entire API.

For example, the method Arrays.asList() returns a List implementation, but we do no care which implementation, as long as it satisfies the List public interface, right?. The implementation can be changed in the future without affecting us, the users of the method, but the actual implementation is hidden from us.

Up to this point, it would appear as if encapsulation depended entirely from the capacity of a programming language to hide details, and therefore, that it could not be achieved without access modifiers, right?

Without Access Modifiers

However, how does a language like Python achieves encapsulation when it does not have access modifiers? Everything is public in Python? Does that mean that encapsulation is not possible?

What if, by convention, we define the public interface of our components and then access the objects' state and behavior only through their public interface? Evidently, for this we need a clear understanding of the abstractions in our problem domain and how these are supposed to be consumed by our users.

To me, it appears as if the interview question was intended to evaluate encapsulation as broader concept, one depending on the definition of very clear abstractions, and not just a as by-product of a language feature like access modifiers.

The Role of Abstraction

That's why, in my opinion, to really understand encapsulation, one must first understand abstraction.

Think, for example, in the level of abstraction in the concept of a car. A car is complex in its internal implementation. They have several subsystem, like a transmission system, a break system, a fuel system, etc.

However, we have simplified its abstraction, and we interact with all cars in the world through the public interface of their abstraction. We know that all cars have a steering wheel through which we control direction, they have a pedal that when you press it you accelerate the car and control speed, and another that when you press it you make it stop, and you have a gear stick that let you control if you go forward of backward. These features constitute the public interface of the car abstraction. In the morning you can drive a sedan and then get out of it and drive an SUV in the afternoon as if it was the same thing.

It is not that you cannot open the hood and see how it all works. However, few of us know the details of how all these underlying features are implemented under the hood, and the truth is that we do not need to know the details to drive a car. All these things are encapsulated under the car abstraction. We only need to know the public interface of the abstraction.

Think of the time when cars did not have a hydraulics directional system. One day, the car manufactures invented it, and they decide it to put it in cars from there on. Still, this did not change the way in which users where interacting with them. At most, users experienced an improvement in the use of the directional system. A change like this was possible because the internal implementation of a car was encapsulated.

This clearly demonstrates that by hiding the details of how the directional systems was implemented, they could safely change it without affecting the public interface of the car and, correspondingly, without affecting the way users interacted with it.

Now, think that car manufactures decided to put the fuel cap below the car, and not in one of its sides. You go and buy one of these new cars, and when you run out of gas you go to the gas station, and you do not find the fuel cap. Suddenly you realize is below the car, but you cannot reach it with the gas pump hose. Now, we have broken the public interface contract, and therefore, the entire world breaks, it falls apart because things are not working the way it was expected. A change like this would cost millions. We would need to change all gas pumps in the world. When we break encapsulation we have to pay a price.

So, as you can see, the goal of encapsulation is to minimize interdependence and facilitate change. You maximize encapsulation by minimizing the exposure of implementation details. The state of a class should only be accessed through its public interface.

The beauty of encapsulation is the power of changing things without affecting its users.

We could say that this ultimate goal depends on careful planning and design. In Java, access modifiers are a way to bring these ideas to life, but in language where this feature does not exist, it is equally possible to achieve encapsulation.

The way i see it , Encapsulation refer to the idea of binding data and method to a single unit called class . However there are two main criteria to bind data and methods . One of them is information hiding, just not the only one . To be perfectly concise i would say the two main criteria are

  1. Low Coupling (ensure by information hiding)
  2. High Cohesion

In the class, attributes and behaviors are placed together. An encapsulation means, that when you create a class, this itself means that you realize encapsulation principle. Because data and behaviors are encapsulated into the class. So data hiding is a major part of the term - encapsulation. And this means access points of the object.

I saw a lots of discussion is already done, just to simplify from my understanding:

Encapsulation Ensures that the behavior of an object can only be affected through its API. It lets us control how much a change to one object will impact other parts of the system by ensuring that there are no unexpected dependencies between unrelated components.Access modifier can used to achieve Encapsulation.

Information hiding Conceals how an object implements its functionality behind the abstraction of its API. It lets us work with higher abstractions by ignoring lower-level details that are unrelated to the task at hand. Abstraction at design level can be used to achieve data hiding.

The easiest definition of encapsulation is "Binding data and code that operates data into a single unit", so that the data can't be accessed directly by outside world.

In structure language like c data is declared at the start of the block and used directly, accessed openly(Any tom, dick and harry can access data). Data hiding is a concept to restrict data access directly and openly to any tom dick and harry.
Encapsulation is one of the way to achieve Data hiding. You achieve data hiding by putting data and function together (Encapsulation).

How you achieve in JAVA, see any getter(), setter() function example in JAVA. Check this

How do getters and setters work?

Encapsulation: Encapsulation is one of the pillar of OOPS, also is superset for the other two terms, data hiding and abstraction. (Data hiding, as the term refers.. Data can only be stored in variables. To hide the data from external world we use data hiding concept. Public, Private, Protected these are three access modifiers provided to us for data hiding. Default is limited to package. Protected limited to inherited class.) ** Private variables are accessible only inside class which means if there is an inner class, there also private variables could be called directly. Only Static Inner Classes can call Static Variables.

Now coming to Abstraction (meaning Intangible). Abstraction is also considered as the process to hide the implementation from user and provide only final result. Example: we have a person class which has “Weight” property. This property is quite tricky because we cannot accept less than 0 weight for a person. Also we cannot accept more than 500 kgs. So hiding the implementation for these will be in the setter method. This thing hiding the implementation details is Abstraction.

** And the Complete Package i.e. making the object private and implementation of logic in setter and getter is called ENCAPSULATION.

  1. ENCAPSULATION is the bundling the data (fields) and behavior (methods) together in classes.
  2. Now, You have to provide access control on the data using access modifiers (private/protected/public or default) which is DATA HIDING. It protects data from the outside world where you do not want to provide the access.
  3. Also, in order to hide the complexity of the operations you must use interfaces in order to achieve ABSTRACTION.

Encapsulation means binding data members and method(behaviour) in a single unit and providing as much information as much user required easily you can say [encapsulation=data hiding+abstraction].

Class is fully encapsulated element in java

Data hiding means declaring data variables as private to secure it from unauthorized access but if you are giving some public setter and getter method for validation.

The process of defining a class by hiding its data from direct access from the outside class member and providing the access only through publicly accessible setter and getter method through proper validation it is called Encapsulation.

From Wikipedia

Encapsulation Encapsulation is an object-oriented programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding.

If a class does not allow calling code to access internal object data and permits access through methods only, this is a strong form of abstraction or information hiding known as encapsulation. Some languages (Java, for example) let classes enforce access restrictions explicitly, for example denoting internal data with the private keyword and designating methods intended for use by code outside the class with the public keyword. Methods may also be designed public, private, or intermediate levels such as protected (which allows access from the same class and its subclasses, but not objects of a different class). In other languages (like Python) this is enforced only by convention (for example, private methods may have names that start with an underscore). Encapsulation prevents external code from being concerned with the internal workings of an object. This facilitates code refactoring, for example allowing the author of the class to change how objects of that class represent their data internally without changing any external code (as long as "public" method calls work the same way). It also encourages programmers to put all the code that is concerned with a certain set of data in the same class, which organizes it for easy comprehension by other programmers. Encapsulation is a technique that encourages decoupling.

Basically Data encapsulation is a process while data hiding is a technique . In encapsulation data can be public or private but in data hiding data is only private. So data hiding uses Encapsulation but it also uses different techniques to keep data permitted to authorized access only. Hope it helps!

Abstraction says that what needed to interact with object.

Encapsulation means encapsulate object properties , state and behaviours into single logical unit called class.

Data hiding says that hiding inner implementation of objects means private methods and properties, the object that use to maintain their state.

The process of binding data members and corresponding methods into a single unit is nothing but encapuslation.

Encapsulation = Data Hiding + Abstraction

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top