I came across this question somewhere which has been kept me engaged thinking why it is behaving this way.
Lets say I have an apex class:
public class TestController {
public String myString{get;set;}
public String getStringmethod1()
{
System.debug('myString'+myString);
return myString;
}
public String getStringmethod2()
{
System.debug('myString'+myString);
if(myString == null)
myString = 'Something';
return myString;
}
public String getStringmethod3()
{
System.debug('myString'+myString);
myString += 'Special';
return mySTring;
}
}
And a visualforce page:
<apex:page controller="TestController">
{!myString}, {!Stringmethod1}, {!Stringmethod2}, {!myString}, {!Stringmethod3}, {!myString}
</apex:page>
I was expecting the output to be
, , Something, Something, SomethingSpecial, SomethingSpecial
But the output is:
, , Something, , SomethingSpecial,
So even after, inside the get methods, setting the myString property value, whenever I try to access the property directly again, I am getting null value. Its not reflecting the change done in getter method.
But again, when I am accessing the same myString property inside a getter method, I am seeing that its holding the changed value, not null anymore.
I am sure I am failing to understand the behavior of getter methods. Could anyone please explain this behavior? Whats happening here?
A property with only a get accessor is considered read-only.