+91 81900 98289

Java Encapsulation

Mark fields private so other classes cannot assign them directly. Offer a method when a change is allowed. That method can reject a blank name or a negative mark before the object stores it.

A getter returns the value. A setter changes it. You do not need a setter for a value that should stay fixed after the constructor, such as an id.

Example

name() returns the private field. main never touches the field directly.

public class Trainee { private String name; Trainee(String name) { this.name = name; } String name() { return name; } public static void main(String[] args) { Trainee t = new Trainee("Karthik"); System.out.println(t.name()); } }
private stops t.name = "" from another class. The only way in is the constructor or a method you wrote. That is the point of the restriction.