Skip to content

Instantly share code, notes, and snippets.

@risou
Created October 11, 2011 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save risou/1277887 to your computer and use it in GitHub Desktop.
Save risou/1277887 to your computer and use it in GitHub Desktop.
カプセル化例
class TwoDimensionsPoint {
private double x;
private double y;
public void setX(double x) {
this.x = x;
}
public double getX() {
return this.x;
}
public void setY(double y) {
this.y = y;
}
public double getY() {
return this.y;
}
}
class TwoDimensionsPoint {
public double x;
public double y;
}
たとえば二次元空間上のある座標の位置を保持するクラスがあったとして、
座標情報を直交座標系で保有しているとする。この場合、フィールドはXとYになる。
ある事情で座標情報を極座標系(θとr)に変えることになった。
このときカプセル化されていない(nonencapsuled.java)だと、
XとYにアクセス(代入or参照)してる全ての箇所に変更が入ることになる。
カプセル化されている(encapsuled.java)と、
内部のデータがrとθに変わっても、setX(),getX(),setY(),getY()の中で
極座標⇔直交座標の変換ロジックを入れれば、
このクラスの外に一切修正が必要ない。
これが「データの形式を簡単に変更できる」ということです。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment