LoginSignup
5
5

More than 5 years have passed since last update.

[オブジェクト指向三大要素] カプセル化がなぜ必要か。

Last updated at Posted at 2015-09-02


個人用備忘録。
カプセル化の最も簡単な例。
以下のコードは、身長を保持(設定/取得)するためのクラス。

Java

class tall {
    private double tall; // カプセル化されたフィールド

    public double getCentimeters() {
        return tall / 10;
    }

    public double getMillimeters() {
        return tall;
    }

    public double getFeets() {
        return tall / 304.8;
    }

    public void setCentimeters(double tall) {
        if( tall < 0 ) throw new Error();
        this.tall = tall * 10;
    }

    public void setMillimeters(double tall) {
        if( tall < 0 ) throw new Error();
        this.tall = tall;
    }

    public void setFeets(double tall) {
        if( tall < 0 ) throw new Error();
        this.tall = tall * 304.8;
    }
}

public class mesureTall {

    public static void main(String[] args) {
        tall t=new tall();
        double tall2;
        t.setFeets(180);
        tall2 =t.getFeets();
        System.out.println(tall2);
    }

}



ひとつの利点。
内部的には、身長はミリメートル単位で保持されているが
内部状態を全く意識することなく、フィートで設定して、
センチメートルで取り出すといったことが可能になる。



ふたつめの利点。
身長が負の値になったりすることはありえないが、
tallの double型変数がパブリックで宣言されていると、
tall = -170 といった非現実的な値も設定できてしまう。

しかし、前記のコードのsetCentimeters()メソッド等に
  public setCentimeters( double tall ) {
    if( tall < 0 ) throw new Error();
    this.tall = tall * 10;
  }
という風に適当なエラーを送出するように設定することで
不自然な値自体を設定できないようにすることが可能になる。





参考
http://oshiete.goo.ne.jp/qa/3019797.html

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5