类的结构之三:构造器(构造方法、constructor)的使用
一、构造器的作用:
1.创建对象
2.初始化对象的属性
封装性的体现:1.将类中的属性xxx私有化,通过public方法获取getXxx()和设置setXxx()此属性的值。
2.不对外暴露的私有的方法。
3.单例模式。(将构造器私有化即在一个类中通过构造器只创建一个对象)
4.如果不希望类在包外调用,可以将类设置为缺省的。
二、说明:
1.如果没有显示的定义类的构造器的话,则系统默认提供一个空参构造器
2.定义构造器的格式:权限修饰符 类名(形参列表){}
3.一个类中多个构造器中可以构成重载
4一旦显式定义了类的构造器之后,系统将不再提供默认的空参构造器
5.一个类中至少有一个构造器
this关键字的使用:
1.this可以用来修饰:属性、方法、构造器
this理解为:当前对象 或 当前正在创建的对象
在类的方法中,我们可以使用"this.属性"或"this.方法"的方式,通常省略
但当方法的形参和类属性同名时,我们需使用”this.变量",表明变量为属性而非形参。
2.this调用构造:
①我们在类的构造器中,可以显式的使用"this(形参列表)"方式,调用指定类的其他构造器。
②构造器中不能通过"this(形参列表)"调用自身
③如果一个类中有n个构造器 最多有n-1个构造器中使用"this(形参列表)"
④规定:"this(形参列表)"必须声明在当前构造器的首行
⑤构造器内部,最多只能声明一个"this(形参列表)",用来调用其它构造器
例题:
public class Account{
private int id;//账号
private double balance;//余额
private double annualInterestRate;//年利率
public Account(int id, double balance,double annualInterestRate){
this.id = id;
this.balance = balance;
this.annualInterestRate = annualInterestRate;
}
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setBalance(double balance){
this.balance = balance;
}
public double getBalance(){
return balance;
}
public void setAnnualIntetestRate(double annualInterestRate){
this.annualInterestRate = annualInterestRate;
}
public double getAnnualInterestRate(){
return annualInterestRate;
}
public void withdraw(double amount){//取钱
if(balance < amount){
System.out.println("余额不足,取款失败");
return;
}
balance -= amount;
System.out.println("成功去出:" + amount);
}
public void deposit(double amount){//存钱
if(balance > 0){
balance += amount;
System.out.println("成功存入:" +amount);
}
}
}
public class Customer{
private String firstName;
private String lastName;
private Account account;
public Customer(String f,String l){
this.firstName = f;
this.lastName = l;
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public Account getAccount(){
return account;
}
public void setAccount(Account account){
this.account = account;
}
}
public class CustomerTest{
public static void main(String[] args){
Customer c = new Customer("Jane","Smith");
Account a = new Account(1000,2000,0.0123);
c.setAccount(a);
c.getAccount().deposit(100);
c.getAccount().withdraw(960);
c.getAccount().withdraw(2000);
System.out.println("Customer [" + c.getLastName() + ","
+ c.getFirstName() + "] has a account: id is"
+c.getAccount().getId() + "annualInterestRate is" +
c.getAccount().getAnnualInterestRate()*100 + "%,balance is" +
c.getAccount().getBalance());
}
}