Encapsulation in Java, To understand the encapsulate concept here developer is going to take two classes by the name Student and Test. In Student developer used
getName() method and through the Test class code has been compiled.
Student.java
[java]
public class Student{
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
}
[/java]
Where created getName() method and it will be retrieved by Test class.
[java]public String getName()[/java]
Where setName() is used to set the name.
[java]public void setName(String name)[/java]
Test.java
[java]class Test{
public static void main(String[] args){
Student s=new Student();
s.setName("SPLESSONS");
System.out.println(s.getName());
}
} [/java]
Where created an object to the previous class Student, through the object name has been given.
[java]Student s=new Student();
s.setName("SPLESSONS");
System.out.println(s.getName()); [/java]
Output:
When compile the code following is the result will be displayed.
[c]
SPLESSONS
[/c]
Abstraction vs Encapsulation in Java
Encapsulation in Java is represented using private, package-private and protected access modifier. It wraps the method data, variables and codes within a class into a single entity. The class and methods outside the wrapper cannot access the code and data defined under the wrapper. In encapsulation object becomes a container for related data variables and methods.
Abstraction in Java is represented by Interface, Abstract class, Abstract methods using
"abstract" keyword. It hides certain details of the object that are not important and display that are essential.
For more detailed overview on abstraction
click here .
For more detailed overview on encapsulation
click here .
For more detailed overview on access modifiers
click here .