Search code examples
javasettergetter

How do getters and setters work?


I'm from the php world. Could you explain what getters and setters are and could give you some examples?


Solution

  • Tutorial is not really required for this. Read up on encapsulation

    private String myField; //"private" means access to this is restricted to the class.
    
    public String getMyField()
    {
         //include validation, logic, logging or whatever you like here
        return this.myField;
    }
    public void setMyField(String value)
    {
         //include more logic
         this.myField = value;
    }