Java / Object-Oriented Programming in Java

Encapsulation and Data Hiding in Java

This tutorial covers the principle of encapsulation in Java. We'll go over how to use encapsulation to protect your data and control how it can be accessed and modified.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Explores OOP principles such as classes, objects, inheritance, polymorphism, and abstraction.

Encapsulation and Data Hiding in Java

1. Introduction

  • Goal of the tutorial: This tutorial aims to educate learners on the principle of encapsulation in Java, which is a crucial part of the OOP (Object-Oriented Programming) concepts. We will learn how to use encapsulation to safeguard our data and to control how it can be accessed and modified.
  • What the user will learn: By the end of this tutorial, users will understand encapsulation's meaning, its importance, and how to implement it in Java programs. We will cover encapsulation, private and public keywords, getters and setters, and demonstrate how to hide data within a class.
  • Prerequisites: Basic knowledge of Java programming, understanding of OOP concepts and Java classes will be beneficial.

2. Step-by-Step Guide

  • Encapsulation: Encapsulation is one of the four fundamental OOP concepts. It refers to the bundling of data with the methods that operate on that data. It is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties' direct access to them.
  • Private and Public Keywords: In Java, encapsulation can be achieved using access modifiers - private, public, and protected. The private keyword is the main actor for encapsulation. It makes the class attributes inaccessible directly from outside the class. The public keyword allows the class attributes to be accessed from outside the class.
  • Getters and Setters: These are the methods used to view and modify the private variables in a class. The getter method returns the variable value, and the setter method sets the value.

3. Code Examples

Example 1: A simple class without encapsulation

public class Employee {
  String name;
  int age;
}

In this example, the class attributes (name and age) can be accessed directly, which is not a good practice.

Example 2: A class with encapsulation

public class Employee {
  private String name;
  private int age;

  //Getter for name
  public String getName() {
    return name;
  }

  //Setter for name
  public void setName(String newName) {
    this.name = newName;
  }

  //Getter for age
  public int getAge() {
    return age;
  }

  //Setter for age
  public void setAge(int newAge) {
    this.age = newAge;
  }
}

In this example, the class attributes (name and age) are declared as private. They can't be accessed directly from outside the class. We have provided public getter and setter methods to access and modify these variables.

4. Summary

  • Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit.
  • Encapsulation can be achieved by declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables.
  • It provides control over the data and helps in achieving data hiding.

Next steps for learning:
- Explore other OOP concepts like Inheritance, Polymorphism, and Abstraction.
- Practice writing encapsulated classes and objects in Java.

Additional resources:
- Oracle Java Documentation
- Java Encapsulation (GeeksforGeeks)

5. Practice Exercises

Exercise 1: Create a Person class with private attributes: name and age. Then provide public getters and setters to manipulate these variables. Create a Person object in a main method and demonstrate getting and setting the attributes.

Exercise 2: Create a BankAccount class with private attributes: accountNumber and balance. Provide public methods for deposit, withdraw, and checkBalance. Make sure balance cannot go negative during withdrawal.

Tips for further practice:
- Try to create more complex classes with more attributes.
- Practice creating classes where some attributes are read-only (only provide getters) and some are write-only (only provide setters).
- Try encapsulating behavior as well (methods) in addition to the data (variables).

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help