例題: BangBuck.java (原始碼)
class Product { public Product() { ... } public void read() { ... } public boolean isBetterThan(Product b) { ... } public void print() { ... } implementation detail }方法中有三類:
class Product{ public Product(); public void read(); public boolean isBetterThan(Product b); public void print(); private String name; private double price; private int score; }
public Product() { name = ""; price = 0; score = 0; }
public Employee() { name = ""; salary = 0; } public Employee(String n, double s) { name = n; salary = s; }預設的建構器沒有參數,另一建構器有兩個參數。 凡是兩個函數有相同名稱,但不同型式的參數,稱為 overloaded。
假如一類別的資料項為一物件,如
class Employee { public Employee(String employeeName, int hireYear, int hireMonth, int hireDay) { ... } . . . private String name; private double salary; private Time hireDate; }hireDate 是屬於類別 Time 的物件。 在 Employee 的建構器中,設定 hireDate 的初值時,用 Time 的建構器, 如
public Employee(String employeeName, int hireYear, int hireMonth, int hireDay) { name = employeeName; salary = 0; hireDate = new Time(hireYear, hireMonth, hireDay, 0, 0, 0); }
例如, raiseSalary 不能直接讀寫 salary (類別 Employee 的私有資料):
static void raiseSalary(Employee e, double percent) { e.salary = e.salary * (1 + percent/100); // error }而必須使用 getSalary 和 setSalary (均為類別 Employee 的公用方法):
static void raiseSalary(Employee e, double percent) { double newSalary = e.getSalary() * (1 + percent/100); e.setSalary(newSalary); }
static void raiseSalary(Employee e, double percent) { double newSalary = e.getSalary() * (1 + percent/100); e.setSalary(newSalary); }假設 harry 是類別 Employee 的物件,調薪用
raiseSalary(harry, 7);改寫 raiseSalary 為個例方法:
class Employee { public void raiseSalary(double percent) { salary = salary * (1 + percent/100); } }調薪必須用
harry.raiseSalary(7);