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.
Example of
encapsulation in java
//save as Student.java
package com.java9m;
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.java9m;
class Test{
public static void main(String[] args){
Student s=new Student();
s.setName("Mohan");
System.out.println(s.getName());
}
}
Compile By: javac -d . Test.java
Run By: java com.java9m.Test
Output: Mohan
No comments:
Post a Comment