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 is 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 the data is processed.

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

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 use 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 summarize 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.

Share on FacebookTweet about this on TwitterShare on LinkedInShare on Google+Digg thisPin on PinterestShare on RedditShare on StumbleUponPrint this pageEmail this to someone

Leave a Reply

3 Comments on "Java Encapsulation Example"

avatar
Sort by:   newest | oldest | most voted
Robert
Guest
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… Read more »
wpDiscuz