Thursday , January 18 2018
Home / Java Programming / What are the set methods and get methods?

What are the set methods and get methods?

What are the set methods and get methods?

The set methods are the methods in a class defined to set or change the values of the instance variables of that class. And the get methods are the methods to retrieve the values of the instance variables.

Consider the Student class

 

public class Student
{
  // instance variables
  private int stdRollNo ;
  private String stdName ;

  // no constructor is defined so default constructor will be called

  // set method to change/set the student roll no
  public void setRollNo(int aRollNo)
  {
    stdRollNo = aRollNo;
  }

  // set method to change/set the student name
  public void setName(String aName)
  {
    stdName = aName;
  }

  // Now we will define the get methods to get the values of instance variables

 // get method to check/get the student rollno
 public int getRollNo()
  {
    return stdRollNo ; 
  }

  // set method to check/get the student name
  public String getName()
  {
    return stdName ;
  }

 
// rest of the class logic
 
} // end-class-student

Now We will create a demo/test class to check the demonstration of above class

Consider a demo class StudentDemo

 

public class StudentDemo
{
  public static void main(String[] args)
  {
    Student aStudent = new Student() ; // default constructor will be called here
   
   // setting a student roll no
   aStudent.setRollNo(2501) ;
  
   // setting a student name
   aStudent.setName("Muhammad Rizwan") ;

  // Now we will demonstrate the get methods

  System.out.println("Student Roll No: " + aStudent.getRollNo() );
  System.out.println("Student Name: " + aStudent.getName() ); 

  // rest of the program logic  
  }
}
(Visited 32 times, 1 visits today)

Check Also

How to parse string in java?

How to parse string in java? Usually in natural language processing, a text is parsed. …