The source code to implement the multiple getters/setters method using accessors is given below. The given program is compiled and executed successfully.
# Ruby program to implement multiple getter/setter
# method using accessors
class Sample
#constructor
def initialize(val1,val2)
@ins_var1 = val1;
@ins_var2 = val2;
end
#accessor get/set method
attr_accessor :ins_var1
#Getter method of ins_var2
attr_reader:ins_var2
end
obj = Sample.new("Hello","Hii");
val1 = obj.ins_var1;
val2 = obj.ins_var2;
print "Value of ins_var11 is: ",val1,"\n";
print "Value of ins_var12 is: ",val2,"\n";
obj.ins_var1 = "Bye";
val1 = obj.ins_var1;
val2 = obj.ins_var2;
print "\n\nValue of ins_var11 is: ",val1,"\n";
print "Value of ins_var12 is: ",val2,"\n";
Output:
Value of ins_var11 is: Hello
Value of ins_var12 is: Hii
Value of ins_var11 is: Bye
Value of ins_var12 is: Hii
Explanation:
In the above program, we created a class Sample. In the Sample class, we implemented constructor and getter, setter methods for multiple instance variables using accessors. Then we created the object of the Sample class with initial values. After that, we used getter/setter methods to get/set the values of ins_var1, ins_var2 variables and print the result.
Program/Source Code:
The source code to implement the multiple getters/setters method using accessors is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we created a class Sample. In the Sample class, we implemented constructor and getter, setter methods for multiple instance variables using accessors. Then we created the object of the Sample class with initial values. After that, we used getter/setter methods to get/set the values of ins_var1, ins_var2 variables and print the result.
need an explanation for this answer? contact us directly to get an explanation for this answer