1. 程式人生 > 其它 >面向物件08封裝詳解

面向物件08封裝詳解

package com.oop.demo04;

//類 private:私有
public class Student {

//屬性私有
private String name; //名字
private int id;//學號
private char sex;//性別
private int age;//年齡
//提供一些可以操作這個屬性的方法!
//提供一些public 的 get、set方法

//get 獲得這個資料
public String getName(){
return this.name;
}

//set 給這個資料設定值
public void setName(String name){
this.name = name;
}

//Alt + insert


public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public char getSex() {
return sex;
}

public void setSex(char sex) {
this.sex = sex;
}

public int getAge() {
return age;
}

public void setAge(int age) {
if(age>120 || age<0){//不合法
this.age = 3;
}else {
this.age = age;
}

}
}



/*
package com.oop;

import com.oop.demo03.Pet;
import com.oop.demo04.Student;
/*
1.提高程式的安全型,保護資料
2.隱藏程式碼的實現細節
3.統一介面
4.系統可維護增加了
*/

public class Application {
public static void main(String[] args) {

Student s1 = new Student();

s1.setName("leo");

System.out.println(s1.getName());

s1.setAge(999);//不合法

System.out.println(s1.getAge());


}
}

*/