The source code to implement the getter method is given below. The given program is compiled and executed successfully.
# Ruby program to implement getter method
class Sample
#constructor
def initialize(val)
@ins_var = val;
end
#Getter method
def GetVal
@ins_var
end
end
obj = Sample.new("Hello");
val = obj.GetVal();
print "Value is: ",val;
Output:
Value is: Hello
Explanation:
In the above program, we created a class Sample. The Sample class contains the constructor and getter method GetVal(). We initialized the instance variables ins_var in the constructor and return the value of the @ins_var variable using GetVal() method. After that, we created the object of the Sample class with the specified value, and get the value of @ins_var variable and assigned it to val and printed it.
Program/Source Code:
The source code to implement the getter method is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we created a class Sample. The Sample class contains the constructor and getter method GetVal(). We initialized the instance variables ins_var in the constructor and return the value of the @ins_var variable using GetVal() method. After that, we created the object of the Sample class with the specified value, and get the value of @ins_var variable and assigned it to val and printed it.
need an explanation for this answer? contact us directly to get an explanation for this answer