Java Encapsulation
w3hello.com logo
Java Basics
Java Introduction
Java Installation
Java Operators
Java Variable Types
Java Loops
Java For Loop
Java While Loop
Java do while loop
Java Continue
Java JButton
Java JTextArea
Java Logical Operators
switch statement in java
Java JPasswordField
Java Year
Java Constructor
Java Basic Syntax
Java JComboBox
Java JToolBar
Java if Statements
Java JMenuBar, JMenu and JMenuItem
Java JDialog
Java JToggleButton
Java JFrame
Java Zip Exceptions
Java DIP - Enhancing Image Brightness
Java JFileChooser
Java Concurrency ExecutorService Interface
Java throw exception
LinkedHashMap in Java
Java Digital Watch
Java instanceof
Java AWT Button
Java For Complete Beginners - loops and arrays
Array vs ArrayList in Java
java.util.Calendar
Java JColorChooser
Java URL Processing
Guide to Java Exception Hierarchy
Java Concurrency ConcurrentMap Interface
Synchronization in Java
Java Internationalization
Java Fetch Image from Oracle Database
Unicode System in Java
Java ActionListener
java.lang.reflect - Interfaces
Java Thread Pool | Thread Pooling in Java
Java Graphics in Applet
Java Convert int to long
Java JSpinner
Java Primitive data type
Java Numeric Literals with Underscore
Inter-thread communication in Java
The Tetris game in Java Swing
Java Applet Basics
Java Convert Binary to Decimal
Static keyword in Java
Java Convert Hex to Decimal
Java JRadioButton
Java XML Overview
Java Concurrency Quick Guide
Java Month enum
Types of Exceptions
Reentrant Monitor in Java
Java Loop Control
Java Access Modifiers
WebSocket in Jetty
Transaction Management in Java JDBC
Java SimpleDateFormat
Java 7 JDBC Improvement
Java FlowLayout
Java AWT Scrollbar
Java Decision Making
Java Database Connectivity with Oracle
Java ZoneId
Java else-if Statements
Java DIP - Laplacian Operator
Top Java Books
Java Date Time - Custom Date Format Patterns
Java static and this Keyword
Java JList
Java Concurrency Lock Interface
Java LocalDate
Creating a thread in Java
Jetty's HTTPClient
Java Package
Displaying image in Applet
Java Overriding
Java AWT Choice
Java SAX Parser Overview
Java Save File in Oracle Database
Java Modifier
Java JDesktopPane
Java Inheritance & Polymorphism
Discuss Java Concurrency
this keyword in java
Java KeyListener
Java Online Training
Java iText
History of Java
Java Basics
Previous : Java HashSet Next : When to use ArrayList and LinkedList in Java

Java Encapsulation


Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.

Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.

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.

Example

Following is an example that demonstrates how to achieve Encapsulation in Java −

/* File name : EncapTest.java */
public class EncapTest {
   private String name;
   private String idNum;
   private int age;

   public int getAge() {
      return age;
   }

   public String getName() {
      return name;
   }

   public String getIdNum() {
      return idNum;
   }

   public void setAge( int newAge) {
      age = newAge;
   }

   public void setName(String newName) {
      name = newName;
   }

   public void setIdNum( String newId) {
      idNum = newId;
   }
}

The public setXXX() and getXXX() methods are the access points of the instance variables of the EncapTest class. Normally, these methods are referred as getters and setters. Therefore, any class that wants to access the variables should access them through these getters and setters.

The variables of the EncapTest class can be accessed using the following program −

/* File name : RunEncap.java */
public class RunEncap {

   public static void main(String args[]) {
      EncapTest encap = new EncapTest();
      encap.setName("James");
      encap.setAge(20);
      encap.setIdNum("12343ms");

      System.out.print("Name : " + encap.getName() + " Age : " +
encap.getAge());
   }
}

This will produce the following result −

Output

Name : James Age : 20

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.

Previous : Java HashSet Next : When to use ArrayList and LinkedList in Java
© Copyright 2018 W3Hello Publishing Limited. All rights reserved.
Contact us | Sitemap