Monday, 24 March 2014

Encapsulation in Java

Posted By: Unknown - Monday, March 24, 2014

Encapsulation is a process of wrapping code and data together into a single unit e.g. capsule i.e mixed of several medicines.
encapsulation in java oops conceptsWe can create a fully encapsulated class by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it.
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.
  1. //save as Student.java  
  2. package com.javatpoint;  
  3. public class Student{  
  4. private String name;  
  5.    
  6. public String getName(){  
  7. return name;  
  8. }  
  9. public void setName(String name){  
  10. this.name=name  
  11. }  
  12. }  
  1. //save as Test.java  
  2. package com.javatpoint;  
  3. class Test{  
  4. public static void main(String[] args){  
  5. Student s=new Student();  
  6. s.setname("vijay");  
  7. System.out.println(s.getName());  
  8. }  
  9. }  
Compile By: javac -d . Test.java
Run By: java com.javatpoint.Test
Output: vijay

0 comments:

Post a Comment

this blog is helpful or not

International

Auto News

Translate

Pages

Popular Posts

Popular Posts

Designed By Templatezy / Sb Game Hacker Apk / MyBloggerThemes