DEV Community

Cover image for Getter ,Setter in Java
Ezhil Abinaya K
Ezhil Abinaya K

Posted on

Getter ,Setter in Java

In Java, Getter and Setter are methods used to protect your data and make your code more secure. Getter and Setter make the programmer convenient in setting and getting the value for a particular data type.

Getter in Java: Getter returns the value (accessors), it returns the value of data type int, String, double, float, etc. For the program's convenience, the getter starts with the word "get" followed by the variable name.

Setter in Java: While Setter sets or updates the value (mutators). It sets the value for any variable used in a class's programs. and starts with the word "set" followed by the variable name.

public class Student{
//private variables and getter setter method =pojo
private int id;
private String name;
private String course;
private int mark;
public Student(int id, String name, String course, int mark) {
        this.id = id;
        this.name = name;
        this.course = course;
        this.mark = mark;
    }
public static void main(String[] args){
Student s1 = new Student(101, "Ezhil", "Java", 85);
Student s2 = new Student(102, "Anban", "Python", 92);
}
public int getId() {
        return id;
 }

public void setId(int id) {
        this.id = id;
}

 public String getName() {
        return name;
 }

 public void setName(String name) {
        this.name = name;
 }

public String getCourse() {
        return course;
}

public void setCourse(String course) {
        this.course = course;
}

public int getMark() {
        return mark;
}

 public void setMark(int mark) {
        this.mark = mark;
}
}
Enter fullscreen mode Exit fullscreen mode

Reference
https://www.geeksforgeeks.org/java/getter-and-setter-in-java/

Top comments (0)