• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer navigation

The Geek Diary

  • OS
    • Linux
    • CentOS/RHEL
    • VCS
  • Interview Questions
  • Database
    • MariaDB
  • DevOps
    • Docker
    • Shell Scripting
  • Big Data
    • Hadoop
    • Cloudera
    • Hortonworks HDP

Java Encapsulation

by admin

Encapsulation is a more useful fundamental OOP concept. The other three are inheritance, polymorphism, and abstraction. Encapsulation in Java is data variables and 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.

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

Example:

/* 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:

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

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

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

Output Name

James Age : 20

Filed Under: Java

Some more articles you might also be interested in …

  1. Basics of Java Variables
  2. jlink: command not found
  3. Java Classes and Objects Introduction
  4. Java Overriding
  5. JavaFX ComboBox: Set a value to the combo box
  6. forever: Server-side JavaScript application that makes sure Node.js applications run indefinitely (restarts after exit)
  7. Java – Networking
  8. Java Character Class
  9. Arrays in Java
  10. Java if and switch-case Statements

You May Also Like

Primary Sidebar

Recent Posts

  • glab Command Examples
  • “glab repo” Command Examples
  • “glab release” Command Examples
  • “glab pipeline” Command Examples

© 2023 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright