1. 程式人生 > >類成員屬性封裝

類成員屬性封裝

屬性私有化,使用private關鍵字。

照Java的開發標準而言,外部要想操作私有屬性,需要按照如下形式定義操作方法:setter、getter:

setter(private String name):public void setName(String n);
getter(private String name):public String getName();
舉例:
class Employee {// 僱員類
	private int number ;
	private String name ;
	private String job ;
	private double salary ;
	private double income ;
	private String phoneNumber;
	private String address;
	public Employee(int number, String name, String job, double salary, double income,String phoneNumber,String address) {
		// TODO Auto-generated constructor stub
		this.number=number;
		this.name=name;
		this.job=job;
		this.salary=salary;
		this.income=income;
		this.phoneNumber=phoneNumber;
		this.address=address;
	}
	public int getNumber() {
		return number;
	}
	public void setNumber() {
		this.number = number;
	}
	public String getName() {
		return name;
	}
	public void setName() {
		this.name = name;
	}
	public String getJob() {
		return job;
	}
	public void setJob() {
		this.job = job;
	}
	public double getSalary(){
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	public double getIncome() {
		return income;
	}
	public void setIncome(double income) {
		this.income = income;
	}
	public String getPhoneNumber() {
		return phoneNumber;
	}
	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public double salary() {
		return salary+income;
	}
	public double income() {
		return this.salary()*12;
	}
	public String getInfo(){
		return "僱員資訊:"+"\n"+
	            "|編號:"+this.getNumber()+"\n"+
				"|姓名:"+this.getName()+"\n"+
	            "|職位:"+this.getJob()+"\n"+
				"|工資:"+this.getSalary()+"\n"+
	            "|佣金:"+this.getIncome()+"\n"+
				"|月薪:"+this.salary()+"\n"+
	            "|年薪:"+this.income()+"\n"+
				"|電話:"+this.getPhoneNumber()+"\n"+
				"|地址:"+this.getAddress()+"\n";		
	}
}
public class Demo {
	public static void main(String[] args) {
		Employee Employee=new Employee(10001,"李白","Java開發工程師",20000.0,5000.0,"18888888888","長安");
		System.out.println(Employee.getInfo());
	}	
}
執行結果:
僱員資訊:
|編號:10001
|姓名:李白
|職位:Java開發工程師
|工資:20000.0
|佣金:5000.0
|月薪:25000.0
|年薪:300000.0
|電話:18888888888
|地址:長安

以後在進行開發的時候,如果有需要,則在setter上加入一些驗證措施,而getter方法只是簡單的將資料返回即可,不需要做任何的驗證。
疑問?為什麼有些沒有在程式之中使用getter()方法?
         在類之中的屬性定義setter、getter操作方法目的就是為了設定和取得屬性的內容,也許某一個操作暫時不使用到取得的操作,不過從開發來講,必須全部提供。以後在定義類的時候,所有的屬性都要編寫private封裝,封裝之後的屬性如果需要被外部操作,則編寫setter、getter。