Encapsulation

In Java, encapsulation refers to the bundling of data and methods that operate on that data into a single unit known as class. It provides a way to control access to the data within those objects.

Getter Methods

  • A getter method is used to retrieve the value of a private data member.
  • It provides controlled access to the data by returning the value.
  • The name of a getter method usually starts with "get" followed by the name of the data member it accesses.

Setter Methods

  • A setter method is used to modify the value of a private data member.
  • It provides controlled access to the data by accepting a new value as a parameter.
  • The name of a setter method typically starts with "set" followed by the name of the data member it modifies.

Encapsulation Example

In this example;

  • The Person class has a private data member "name" which is encapsulated.
  • The constructor is initializing the value of "name".
  • In main class, we create Person object which can access public data members.
  • The getName method allows you to access "name" using dot operator in main function.
  • The setName method sets the value of "name".

This demonstrates how encapsulation allows you to control access to class fields and maintain data integrity.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Easy

Which of the following is a best practice in programming?

10 XP~2 min
Exercise 2 of 2Easy

Code that is easy to read and understand is called ___ code.

10 XP~2 min