Java 关键字之this

来源:互联网 发布:营改增减税数据 编辑:程序博客网 时间:2024/06/08 09:28


this 是什么?

this 是一个引用类型,

在堆中的每一个java对象上都有this,

this 保存内存地址指向自身

public classThisTest01{

public static voidmain(string[] args){

//创建对象

MyDate t1=newMyDate(2008,8,8);

System.out.println(t1.year+”年”+t1.month+”月”+t1.day+”日”);

//创建对象

MyDate t2=newMyDate(2012,12,12);

System.out.println(t2.year+”年”+t2.month+”月”+t2.day+”日”);

}

}

//日期

Class MyDate{

//Field

Int year;

Int month;

Int day;

//Constructor

MyDtae(){

MyDate(int  _year,int _month,int  _day){

year=_year;

month=_month;

day=_day;

}

}

this能用到哪些地方?

One :可以用在成员方法中

Two:可以用在构造方法中

用在成员方法中,this就是当前对象

Public classthisTest02{

Public static voidmain(string[] args){

//创建对象

Employee e=newEmployee(7639,”smith“);

//工作

e.work();

//创建对象

Employee e1=newEmployee(7670,”mike“);

//工作

e1.work();

}

Class Employee{

//员工编号

Int empNo;

//员工名称

String empName;

//Constructor

Employee(){}

Employee(int_empNo,string _empName){

empNo=_empNo;

empName=_empName;

}

//提供一个员工工作的方法。

//this 用在成员方法中,谁去调用这个成员方法,this就代表谁

This 指的是当前对象。

Public void work(){

System.out.println(empName+“在工作”);

--优化后(this.可以省略)

System.out.println(this.empName+“在工作”);

}

}

This 可用来区分成员变量和局部变量

Public classThisTest03{

Public static voidmain(string[] args){

Manager m1=newManager("king”);

Manager m2=newManager();

m2.setName(“Ford”);

System.out.println(m1.getName);

System.out.println(m2.getName);

 

}

}

Class Manager{

//Field

private stringname;

//Constructor

Manager(){}

Manager(stringname){

this.name=name;

}

//Method

//成员方法

Public voidsetName(string name){

this.name=name;

}

//成员方法

Public stringgetName(){

return this.name;

}

this 不能用在静态方法中

静态方法的执行根本不需要java对象的存在,直接使用类名.的方式访问。

而this代表的是当前对象,所以静态方法中根本没有this

 

可以用在构造方法中

语法:this(实参),必须出现在构造方法的第一行

通过一个构造方法去调用另一个构造方法,目的:代码重用

 

需求:在创建日期对象时,默认日期是:1970-1-1

public classThisTest04{

public static voidmain(string[] args){

MyDate t=newMyDate();

System.out.println(t.year+”年”+t.month+”月”+t.day+”日”);

}

Class MyDate{

Int year;

Int month;

Int day;

//Constructor

MyDtae(){

this(1970,1,1);

变更前:(同样效果)

//this.year=1970;

//this.month=1;

//this.day=1;

}

MyDate(int  _year,int _month,int  _day){

year=_year;

month=_month;

day=_day;

}

}

0 0
原创粉丝点击