getters/setters

Java does not support getters/setters in a special way at the syntax level. Just use usual methods with following the Java bean naming convention: getXxx()/setXxx(value). For boolean data, the getter name may have a prefix "is": isXxx().

Usually getters/setters are used as wrapper on private data. Thus you can

  • dissallow change data from outside of class
  • do additional job on get/set events
  • change return type to a more appropriate type in child classes

Remember, objects are passed by reference. When getter returns a mutable object appears opportunity that object will be modified externally and workflow will be crushed. In this case safely will be to return the object copy. Using interfaces and wrappers also can resolve this problem.

public class Obj {

    private int field1;
    private boolean isOk=false;
    protected  Number field2 = 23;

    public int getField1(){return field1;}
    public void setField1(int v){ field1 = v;}
    
    public Number getField2(){
        return field2;
    }

    // read-only property, changing somewhere inside the class
    public boolean isOk() {return isOk;}
    //...
}

public class Obj2 extends Obj {
    public Obj2() {
        field2 = 45L;
    }

    // change return type
    @Override
    public Long getField2() {
        return (Long)field2;
    }
}