Getters and Setters in Scala
Getter and Setter in Scala are methods that helps us to get the value of variables and instantiate variables of class/trait respectively. Scala generates a class for the JVM with a private variable field and getter and setter methods. In Scala, the getters and setters are not named getXxx and setXxx, but they are used for the same purpose. At any time, we can redefine the getter and setter methods ourself.
Setters
Setter are a technique through which we set the value of variables of a class. Setting an variable of class is simple it can be done in two ways :-
- First if the members of a class are accessible from anywhere. i.e no access modifier specified.
Example:
class Student
{
var student _ name : String = " "
var student _ age : Int = 0
var student _ rollno = 0
}
object Main
{
def main(args : Array[String])
{
var obj = new Student()
obj.student _ name = "Yash"
obj.student _ age = 22
obj.student _ rollno = 59
println( "Student Name: " + obj.student _ name)
println( "Student Age: " + obj.student _ age)
println( "Student Rollno: " + obj.student _ rollno)
}
}
|
Output:
Student Name: Yash
Student Age: 22
Student Rollno: 59
For security reasons it is not recommended. As accessing the members of class directly is not a good a method to initiate and change the value as it will allow others to identify the variable.
- Second if the members of a class are defined as private. Initiation of the variables is done by passing the variable to public method of that class using the object of the class.
Example:
class Student
{
var student _ name : String = " "
var student _ age : Int = 0
private var student _ rollno = 0
def set _ roll _ no(x : Int)
{
student _ rollno = x
}
}
object GFG
{
def main(args : Array[String])
{
var obj = new Student()
obj.student _ name = "Yash"
obj.student _ age = 22
obj.set _ roll _ no( 59 )
println( "Student Name: " + obj.student _ name)
println( "Student Age: " +obj.student _ age)
println( "Student Rollno: " +obj.student _ rollno)
}
}
|
Getters
Getters are a technique through which we get the value of the variables of a class.
Last Updated :
20 Jun, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...