Day 006 p440

this
this 大部分可以省略
this 区分局部变量和实例变量‘ (为了见名知意 同名的时候)
在实例方法中,为了区分局部变量和实例变量中是不能省的
this 除了使用在实例方法中,还能用在构造方法中
以后写代码都要封装,属性私有化,对外提供seeter and getter
class Date{
private int year;
//年
private int mouth;
//月
private int day;
//日
// 无参调用构造方法
public Data(){
this(1970,1,1);
}
public Date(int year ,int mouth,int day){
this.year = year;
this.mouth = mouth;
this .day = day ;
}
public void setYear(int Year){
this.year = year;
}
public int getYear(){
return year;
}
}
}
this(实际参数列表)
上面的代码就是
新语法:通过当前的构造方法去调用另一个本类的构造方法,
可以使用以下的语法格式
this(实际参数列表)
this() 的调用必须是构造方法的第一行
作用 : 代码的重复使用
总结:this
-
可以使用在实例方法中, 也可以使用在构造方法中,不能使用在静态方法中
-
出现在实例方法中,代表的时当前的对象
-
大部分的情况下可以省略。但是区分局部变量和实例变量的时候不能省略
-
this()这种代码只能出现在构造方法的第一行,表示当前构造方法调用本类其他的方法,目的是代码复用
一个银行的账号设置
public class bandmoney {
public static void main(String[] args) {
Account a =new Account("2018214473",10000000,0.0314);
Customer c=new Customer("zhang junlong",a);
c.getAct().deposit(1000);
c.getAct().withdraw(9555);
c.getAct().withdraw(1000000000);
}
}
class Account {
private String ID;
//账号id
private double balance;
//账号余额
private double annual;
//年利率
// 构造方法
public Account(){
}
public Account(String id,double balance,double annual){
this.ID=id;
this.balance =balance;
this.annual =annual;
}
public void setID(String id)
{
this.ID=id;
}
public String getID() {
return this.ID;
}
public void setBalance(double balance) {
this.balance=balance;
}
public double getBalance() {
return this.balance;
}
public void setAnnual (double annual){
this.annual = annual;
}
public double getAnnual () {
return annual;
}
//方法 存款
public void deposit(double money)
{
this.setBalance(this.getBalance()+money);
System.out.println("成功存入"+money);
}
//方法 取钱
public void withdraw(double money){
if(this.getBalance()>money){
this.setBalance(this.getBalance()-money );
System.out.println("成功取出来了"+money+"的钱");
}
else {System.out.println("余额不足 取不了钱");
return;
}}
}
class