+ Start a Discussion
Nirav MNirav M 

Understanding setter and action methods

Following is my Apex class:

public class Calculator {
    public Decimal Operand1 {get;set;}
    public Decimal Operand2 {get;set;}
    public Decimal Result   {get;set;}
    public String errMessage {
        get { return errMessage;}
        set { errMessage='No Error';
              system.debug('in setter errMessage: '+ errMessage);}
    public  Void Addition (){
    public  Void Substraction (){
    public  Void Multiplication (){
    public  Void Division (){
        if (Operand2 != 0 ){
            errMessage= ' Operand can not be Zero';
            system.debug('in Action method errMessage: '+ errMessage);

And Following is from Anonymous block to run the above class.
Calculator Calc = new Calculator();
system.debug('Final Result: ' + Calc.Result);
system.debug('Final errMessage: ' + Calc.errMessage);

Why I don't see the error message "Operand can not be Zero" when i run the above.  
Nirav MNirav M
Hmm I did not get any answer. May be i did not ask the question correctly.
I just want to know what is wrong with it. Why it is not assigning correct value to errMessage variable.
Footprints on the MoonFootprints on the Moon
Hi Nirav,
Got your point.
The error is being displayed as "No Error", because at line errMessage= 'Operand can not be Zero'; you are setting some value to errMessage,
which will eventually direct towards setter method. Inside setter, you are overriding 'Operand can not be Zero' this value with 'No Error'.

To have proper error message simple change errMessage declaration to -
public String errMessage { get; set; }

Let me know if this helps!