4.this关键字

来源:互联网 发布:淘宝怎样付款 编辑:程序博客网 时间:2024/05/16 17:54
1.this 关键字:

   1.this是什么?

      this是一个引用类型

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

      this保存内存地址指向自身



 2.this用在什么地方? 

       第一:this可用在成员方法中,代表当前对象

       第二:this可用在构造方法中

                     语法:this(实参)

                                通过一个构造方法去调用另一个构造方法

                                目的:代码重用

                                 注意:this(实参)必须出现在构造方法第一行

this用在成员方法中

public class test{public static void main(String[] args){//创建对象Person p1 = new Person("gyc",1);    p1.work();}}class Person{String ename;int empno;Person(){}Person(String _ename, int _empno){//员工姓名ename = _ename;//员工编号empno = _empno;}//提供一个员工工作的方法public void work(){//this在成员方法中,谁调用这个成员方法,this就代表谁//this指的就是当前对象System.out.println(this.ename +"在工作");//System.out.println(ename +"在工作");  this.可以省略}}

this用在构造方法中

public class test{public static void main(String[] args){//创建对象MyDate t1 = new MyDate(2008,8,8);System.out.println(t1.year+"年"+t1.month+"月"+t1.day+"日");        MyDate t2 = new MyDate();System.out.println(t2.year+"年"+t2.month+"月"+t2.day+"日");}}class MyDate{//Fieldint year;int month;int day;//Constructor//需求:在创建日期对象的时候,默认日期是:1970-1-1MyDate(){           this(1970,1,1);}MyDate(int _year, int _month, int _day){ year = _year; month = _month; day = _day;}}




原创粉丝点击