隱藏資料--封裝的基本原則

封裝的基本原則:

將instance variables標示為private

將getters與setters標示為public --> 利用getters和setters控制存取動作

這樣能維持安全性

e.g.

class GoodDog {
private int size;

public int getSize() {
return size;
}

public void setSize(int s) {
size = s;
}

void bark() {
if (size > 60) {
System.out.println("Wooof! Wooof!");
} else if (size > 14) {
System.out.println("Ruff! Ruff!");
} else {
System.out.println("Yip! Yip!");
}
}
}

class GoodDogTestDrive {

public static void main (String[] args) {
GoodDog one = new GoodDog();
one.setSize(70);
GoodDog two = new GoodDog();
two.setSize(8);
System.out.println("Dog one: " + one.getSize());
System.out.println("Dog two: " + two.getSize());
one.bark();
two.bark();
}

}

//console result:

Dog one: 70

Dog two: 8
Wooof! Wooof!
Yip! Yip!



留言

這個網誌中的熱門文章

如何在macbook pro上安裝Eclipse、tomcat、mariadb、MySQLWorkbench?

求1000和495的最大公因數

如何在mac版的Eclipse workspace中找到.metadata?