Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Encapsulation
1. Contribute Us | Ask Question | login
JavaTpoint
Subscribe Us
91-9990449935
0120-4256464
Home
Core Java
Servlet
JSP
EJB
Struts2
Mail
Hibernate
Spring
Android
Design P
Quiz
Projects
Interview Q
Comment
Forum
Training
Basics of Java
Java OOPs Concepts
Advantage of OOPsNaming ConventionObject and ClassMethod OverloadingConstructorstatic
keywordthis keywordInheritance(IS-A)Aggregation(HAS-A)Method OverridingCovariant
Return Typesuper keywordInstance Initializer blockfinal keywordRuntime
PolymorphismDynamic Bindinginstanceof operatorAbstract classInterfaceAbstract vs
InterfacePackageAccess ModifiersEncapsulationObject classObject CloningJava ArrayCall
By Valuestrictfp keywordAPI DocumentCommand Line ArgArray Quiz-1Array Quiz-2OOPs
Quiz-1OOPs Quiz-2OOPs Quiz-3OOPs Quiz-4
Java StringJava RegexException HandlingJava Inner
classesMultithreadingSynchronizationI/OSerializationNetworkingAWTEvent
HandlingSwingLayoutManagerAppletReflection APICollectionJDBCJava New
FeaturesRMIInternationalization
next »« prev
2. Encapsulation in Java
Encapsulation in java is a process of wrapping code and data together into a single
unit, for example capsule i.e. mixed of several medicines.
We can create a fully encapsulated class in java 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.
The Java Bean class is the example of fully encapsulated class.
Advantage of Encapsulation in java
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. 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
Next TopicObject class in java
« prevnext »
Like/Subscribe us for latest updates or new sletter ↑Top
Tutorials
» Core Java Tutorial
» Servlet Tutorial
» JSP Tutorial
» Mail API Tutorial
» Design Pattern Tutorial
» Struts Tutorial
» Spring Tutorial
» Hibernate Tutorial
» Android Tutorial
» JavaScript Tutorial
» SQL Tutorial