A non-static class member is also called an instance variable in case of the field or an instance method in case of a method. It can be accessed only via reference to the object followed by a dot "." We have seen several such examples already.
In line with the long-established tradition, the fields of an object are usually declared private. If necessary, the methods set() and/or get() are provided to access such private values. They are often called setters and getters as they set and get values of private fields. Here is an example:
public class MyClass {
private int field1;
private String field2;
public void setField1(String val){
this.field1 = val;
}
public String getField1(){
return this.field1;
}
public void setField2(String val){
this.field2 = val;
}
public String getField2(){
return this.field2;
}
//... other methods are here
}
Sometimes, it is necessary to make sure that the object state cannot be changed. To support such a case, programmers use a constructor to set the state and remove setters:
public class MyClass {
private int field1;
private String field2;
public MyClass(int val1, String val2){
this.field1 = val1;
this.field2 = val2;
}
public String getField1(){
return this.field1;
}
public String getField2(){
return this.field2;
}
//... other non-setting methods are here
}
Such an object is called immutable.