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;}}
阅读全文
0 0
- 4.this关键字
- 关键字this
- this关键字
- this关键字
- this 关键字
- this 关键字
- this关键字
- this关键字
- this 关键字
- this 关键字
- this 关键字
- this关键字
- 关键字this
- 关键字this
- this 关键字
- this 关键字
- this关键字
- this关键字
- Python的多继承
- 1071: 骑马修栅栏
- Java字符串学习总结
- poj 1734(最小环+路径)
- 编译和链接基础问题
- 4.this关键字
- cocos2d中缓动action的UI示意
- python从入门到实践:9-6 冰淇淋小店
- Leetcode 99. Recover Binary Search Tree O(1)
- 我的项目管理模型
- Android实现来电和去电的监听
- 稀疏矩阵存储格式总结+存储效率对比:COO,CSR,DIA,ELL,HYB
- Matlab 实现字符串分割(split)
- Akka(20): Stream:异步运算,压力缓冲-Async, batching backpressure and buffering