HomeContact

How to do Encapsulation in Java Getter,Setter

Published in Java
May 12, 2023
1 min read

One of the methods used in Java is encapsulation. This prevents direct data modification in the class and allows changes only by methods.

Using this method has the following advantages.

  1. Better control over the properties/methods in the class.
  2. The properties in the class can be set for read-only/write-only.
  3. Flexibility (not affecting other parts, only part of the code can be changed.)
  4. Enhanced data security.

Sample

public class Test {
private String site; // Setting restrictions on external access.
public String getSite() { // get method
return site;
}
public void setSite(String newSite) { // set method
this.site = newSite;
}
}
public static void main(String[] args) {
Test myObj = new Test();
myObj.site = "google.com"; // error.
myObj.setSite("google.com");
// System.out.println(myObj.site);
}

Tags

#Java#java.lang

Share


Previous Article
How to do Recursions in Java

Topics

Java
Other
Server

Related Posts

How to use BigInteger in Java - 2
May 31, 2023
1 min