javaのgetterとsetterの役割について改めて学びなおしたので、書き留めておきます。
1.getterの役割
あるクラスから、別のクラスに変数(呼び出し元のメンバ変数)を呼び出すとき、呼び出し元のクラスや、その変数自体がprivateであった場合に使用されるのがgetterメソッドです。そのまま呼び出してもprivateで宣言されている場合変数を呼び出すことができないため、その変数をreturnで返すpublicなメソッドを作成し、そのメソッドを呼び出すことで間接的にprivateなメンバ変数を呼び出す必要があります。 以下は例文です
public class Sample1{
public static void main(String args[]){
Sample10 sample = new Sample10();
System.out.println(sample.getStr());
}
}
public class Sample2{
private String str = "サンプル";
public String getStr(){
return this.str;
}
}
実行結果はサンプルと出力されます。
2.setterの役割
あるprivateなメンバ変数を、呼び出し先から書き換えるために用いられるpublicなメソッドがsetterメソッドです。 先ほどの例にsetterを用いると以下のようになります。
public class Sample1{
public static void main(String args[]){
Sample10 sample = new Sample10();
sample.setStr("さんぷる");
System.out.println(sample.getStr());
}
}
public class Sample2{
private String str = "サンプル";
public void setStr(String str){
this.str = str;
}
public String getStr(){
return this.str;
}
}
実行結果はさんぷると出力されます。


