Javatpoint Logo

getter and setter

By: richam*** On: Mon Mar 13 11:08:08 IST 2017     Question Reputation0 Answer Reputation0 Quiz Belt Series Points0  0Blank User
in encapsulation, where should we use only getter and where should we use both. As example, we have student class and the attributes are name, rollNo, and marks. All are private. Now, if just use getter and setter for marks and only getter for name and rollNo. what does it mean? Up0Down

 
Getter or Accessor methods and Setter or Mutator methods are public methods.

Getter or Accessor methods are used to retrieve the values of a private variable. In the question, if name and rollNo are already assigned values, then you can use these methods to get the values. They must have a return type. For example:

public String getName(){
return name; // this returns the value stored in name variable to the caller method
}

public int getRollNo(){
return rollNo; // this returns the value stored in rollNo variable to the caller method
}

Setter methods are used to change the value of private variables. They do not have return types. For example,

public void setMarks(int marks){
this.marks = marks; // assigns some values to the marks variable
}

The this keyword is used to overcome name-space collisions.

Hope this answers your questions.

Regards.
Image Created0Down

By: [email protected] On: Tue Mar 14 14:32:19 IST 2017 Question Reputation0 Answer Reputation0 Belt Series Points0 0User Image
Are You Satisfied :0Yes0No