Header Ads

Setter and Getter Methods in Java | How to Create Setter and Getter Methods in Java

 

A setter and getter are methods used to retrieve and update the values of private field in a class. Here is an example of how to implement getter and setter methods for a Student Class with three attributes rollno, Name, and GPA

1. Create Class Student

2. Create Three Attribute Roll No, Name and GPA

3. Create Constructor to Initialize the Attributes

4. Create Setter and Getter Methods of Each Attributes

Program Source Code

package Student.com;

public class Student {

private int rollno;

private String name;

private double gpa;

public Student() {

rollno = 0;

name = "Null";

gpa = 0.0;

}

public void setRollno(int rno) {

this.rollno = rno;

}

public int getRollno() {

return this.rollno;

}

public void setName(String n) {

this.name = n;

}

public String getName() {

return this.name;

}

public void setGPA(double g) {

this.gpa=g;

}

public double getGPA() {

return this.gpa;

}

public static void main(String[] args) {

// TODO Auto-generated method stub

Student stdobj = new Student();

stdobj.setRollno(10);

stdobj.setName("Abdullah");

stdobj.setGPA(3.5);

System.out.println("Rollno :"+stdobj.getRollno());

System.out.println("Name :"+stdobj.getName());

System.out.println("GPA :"+stdobj.getGPA());

}

}

Explanation 

In this example the rollno name and gpa fields are marked as private

 to ensure encapsulation to access these fields from outsides the class.

 We define Public getter and Setter methods


The Setter methods are set the values of the fields to the specified 

input. The getter methods simply return the values of the 

corresponding fields.


Related Video



No comments

Powered by Blogger.