getter setter confused

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 { 
    set;
    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.


A test shows that you'll get the value 'first' in your page.

I'm not sure why the automatic one overrides your specific get method, but the upshot is that you shouldn't use both in order to avoid confusion, especially since the second way would be completely redundant if you've followed your member variable declaration with {get; set;}.

The documentation on Apex Properties doesn't include anything regarding this 'doubling up' of a getter.

Tags:

Visualforce