構(gòu)造方法
構(gòu)造方法是一種特殊的方法,沒有返回值,函數(shù)名必須與類名相同。
一個類里可以創(chuàng)建多個構(gòu)造方法,如果不創(chuàng)建,系統(tǒng)會自動創(chuàng)建一個空的沒有參數(shù)的構(gòu)造方法。下面由一個例子來說明構(gòu)造方法中參數(shù)不同時的作用:
class Employee{
//設(shè)置Employee類的屬性
private int id;
private String name;
private double price;
private String branch;
//無參的構(gòu)造方法
Employee(){
System.out.println("設(shè)置無參信息");
}
//可不可以把判斷輸入信息的方法寫到構(gòu)造函數(shù)中?
Employee(int id){
if(this.id>0)
{
this.id = id;
System.out.println("設(shè)置單參信息 " + this.id);
}
else{
System.out.println("輸入有誤!");
}
}
Employee(int id, String name){
this.id = id;
this.name = name;
System.out.println("設(shè)置雙參信息 " + this.id + " " + this.name);
}
Employee(int id, String name, double price, String branch){
//在這個構(gòu)造方法中,JVM會先調(diào)用setId方法來給id屬性數(shù)值
this.setId(id);
this.setBranch(name);
this.setPrice(price);
this.setBranch(branch);
// this.id = id;
// this.name = name;
// this.price = price;
// this.branch = branch;
System.out.println("設(shè)置四參信息 " + this.id + " " + this.name + " " + this.price + " " + this.branch);;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
}
public class Workers {
public static void main(String[] args){
//聲明一個對象,并實例化
Employee employee1 = null;
System.out.println("******************************");
employee1 = new Employee();
Employee employee2 = new Employee(-2010);
Employee employee3 = new Employee(2010, "員工");
Employee employee4 = new Employee(2010, "員工2", 45000, "技術(shù)部");
}
}
這個程序的輸出結(jié)果是:
******************************
設(shè)置無參信息
輸入有誤!
設(shè)置雙參信息 2010 員工
設(shè)置四參信息 2010 null 45000.0 技術(shù)部
這個程序能夠說明,構(gòu)造方法是在一個對象被實例化的時候被調(diào)用的。
在構(gòu)造方法中,我還有個問題:
可不可以把判斷輸入信息是否正確的方法寫到構(gòu)造函數(shù)中?
判斷輸入信息是否正確寫在set方法中和寫在構(gòu)造方法中有什么不同的效果。
以下是我自己的看法不知道是否正確?
我覺得把判斷信息寫在構(gòu)造方法中和set方法中的作用是一樣的,只不過寫在set方法中必須把構(gòu)造方法中的賦值語句由this.屬性名=屬性名 換為 this.set屬性名(屬性名)就可以了!
但不知道這樣做可不可以,從程序上來說是可以的,但在實際中這樣做是否可行,還請大蝦們指教。
posted on 2010-10-14 00:52
tovep 閱讀(813)
評論(0) 編輯 收藏