X

Java Encapsulation Example

This example demonstrates the usage of encapsulation in Java programming language

What is Encapsulation

Encapsulation is all about wrapping variables and methods in one single unit. Encapsulation is also known as data hiding. Why? Because, when you design your class you may (and you should) make your variables hidden from other classes and provide methods to manipulate the data instead. Your class should be designed as a black-box. You have access to several methods from outside (classes) and a return type for each of those methods. All you need to know about this class is the name of the method and the return type. In other words – you give the class some data and get new data as response, without caring about the internal mechanisms used for data processing.

Encapsulation is one of the four major concepts behind object-oriented programming (OOP). OOP questions are very common on job interviews, so you may expect questions about encapsulation on your next Java job interview.

To achieve encapsulation in Java:

  • Declare the variables of a class as private.
  • Provide public setter and getter methods to modify and view the variables values.



 

Java Encapsulation Example

Java encapsulation example

Following example demonstrates encapsulation in Java. The Car class has two fields – name and topSpeed. Both are declared as private, meaning they can not be accessed directly outside the class. The getter and setter methods : getName, setName, setTopSpeed etc. are declared public. Those methods are exposed to “outsiders” and can be used to change and retrieve data from the Car object. Note, we have one method to set the top speed of the vehicle and two getter methods to retrieve the max speed value either in MPH or KMH. This is what encapsulation does – it hides the implementation and gives us the values we want

package net.javatutorial;

public class Car {
	
	private String name;
	private double topSpeed;
	
	public Car() {}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setTopSpeed(double speedMPH) {
		topSpeed = speedMPH;
	}
	
	public double getTopSpeedMPH() {
		return topSpeed;
	}
	
	public double getTopSpeedKMH() {
		return topSpeed * 1.609344;
	}

}

The main program creates a Car object with given name and uses the setter method to store the top speed for this instance. Now we can easily get the speed in MPH or KMH without caring about how speed is converted in the Car class.

package net.javatutorial;

public class EncapsulationExample {

	public static void main(String[] args) {
		Car car = new Car();
		car.setName("Porsche Cayenne 4.8-litre V8");
		car.setTopSpeed(173.0d);

		System.out.println(car.getName() + " top speed in MPH is " + car.getTopSpeedMPH());
		System.out.println(car.getName() + " top speed in KMH is " + car.getTopSpeedKMH());
	}

}

This is the output of the example

Porsche Cayenne 4.8-litre V8 top speed in MPH is 173.0
Porsche Cayenne 4.8-litre V8 top speed in KMH is 278.416512

Lets summarise the benefits of encapsulation:

  • The fields of a class can be made read-only or write-only.
  • A class can have total control over what is stored in its fields.
  • The users of a class do not know how the class stores its data. A class can change the data type of a field and users of the class do not need to change any of their code.
5 1 vote
Article Rating
filip:

View Comments (3)

  • You give a fair definition of encapsulation, but your interpretation after that is highly debatable. If encapsulation is about hiding the internal structure of your object, then clearly both getters and setters break this encapsulation.

    Let's think about it this way: In your Car example do I (as the user of your object) know the internal structure of a Car? Of course I do, because I know it consists of a "Name" and a "Top Speed". I *have* to know it, to use it. You did not hide anything from me.

    So, how could we change the Car to really hide the internal structure? It would have to be modified to *do* the things we want with it. There is only 1 function you want, that is to display the car's name with top speed in mph. This function, and only this function should be then bundled with the Car as "Car.display()" for example.

    • Thank you for your comment Robert,
      I appreciate your effort making this tutorial better. Lets keep the discussion going :)
      I have to disagree on following:

      (1) In my Car example I do not pretend the internal structure of the class is hidden. As you already mentioned in your comment - "you have to know it to be able to use the object". What is hidden tough, are the internal mechanisms the data is processed, not the structure itself.

      (2) using getter and setter methods is an important concept of encapsulation. They do not break encapsulation, it's the opposite - they provide controlled access to our data. Replacing those methods with only one method - Car.display() for instance, will render the example incomplete

      • Thank you for your reply. Let me try just one more time to point out some internal inconsistencies of what you are saying.

        1. You say that the internal mechanisms are hidden. But are they really? Is there any difference in the above Car class to just making both instance variables public? There is none, you get exactly the same functionality.

        You used the words "black-box" in your introduction. Do you thing the Car class above is a black-box?

        Remember, we're talking about the Car class above, not some potential future Car class.

        2. Getter/setters are *not*, in any shape or form, a concept of encapsulation. Getter/setters are a work-around we developers came up with after someone convinced us that it is not cool to make instance variables public.

        Controlling access is a different thing. You are probably thinking about preserving the Class Invariant. Encapsulation is not about Class Invariants, it's about preventing coupling to either the internal structure or data of the object.

Related Post