Encapsulation is a process of wrapping code and data together into a single unit e.g. capsule i.e mixed of several medicines.
Java Bean is the example of fully encapsulated class.
Advantage of Encapsulation
By providing only setter or getter method, you can make the class read-only or write-only.
It provides you the control over the data. Suppose you want to set the value of id i.e. greater than 100 only, you can write the logic inside the setter method.
Simple example of encapsulation in java
Let's see the simple example of encapsulation that has only one field with its setter and getter methods.
- //save as Student.java
- package com.javatpoint;
- public class Student{
- private String name;
- public String getName(){
- return name;
- }
- public void setName(String name){
- this.name=name
- }
- }
- //save as Test.java
- package com.javatpoint;
- class Test{
- public static void main(String[] args){
- Student s=new Student();
- s.setname("vijay");
- System.out.println(s.getName());
- }
- }
Compile By: javac -d . Test.java Run By: java com.javatpoint.Test
Output: vijay
0 comments:
Post a Comment