getter setter confused

I want to know about the setter and getter. I know that it is a properties of declaring variable but some time I get confused. Presently I am using a sample of code that is below:

public with sharing class hello
    public String temp{set;get;} 
    public hello(){
        temp = 'first' ;

    public String gettemp(){
        return 'second' ;

So I want to know that when I use temp on VFP than what value will show on page, what is reason for that, and what is the difference between temp and gettemp?

Ashlekh Gera


You might want to read about getters, setters and VF page order of execution (that’s a very long read with lots of examples though). There’s also an interesting (if a bit hidden) topic in Apex Reference on how names (of variables and methods) are resolved

Your temp variable gets assigned a value in the constructor because constructor is the first thing that fires. Since you’ve defined the automatic getter and setter. the gettemp() is now redundant – actually I have no idea how to “force call” this method from Visualforce (not counting action methods etc).

I’d say decide on one convention and stick to it? Either

  • shortcut with writing {get;set;} (with variations like {get;private set;} or
  • full getVariable/setVariable methods?

There’s also this crazy syntax of getters that initialize the variable first time they’re used – it has some uses (especially when you want to make constructor “thin” and not fire off queries that might not be used on the page. Still – I prefer making explicit getVariable methods in such situations anyway. That’s more of philosophical matter about getters/setters in general 😉

public Account acc { 
    get {
        if (acc == null) acc = [SELECT Id FROM Account LIMIT 1];
        return acc;

As you can see from the last link – the {get; set;} thing is “new” 😉 It was introduced to Visualforce in 2008. There might be still some ancient VF pages with version 14 or something that can’t use it unless their version is upgraded. Before Summer ’08 you had to explicitly write out getter/setter for each variable you planned to use on VF page.

Source : Link , Question Author : D-Horse , Answer Author : eyescream

Leave a Comment