Java面向对象.This ——恋天小结

This定义

定义
this是每个对象中,保存自身内存地址的一个引用类型的成员变量

this就表示这个对象自己

this不能出现在静态上下文中,只能出现在成员方法中

用哪个对象调用的成员方法,那么成员方法中的这个this 就表示哪个对象

This用法

用法
1 this用在成员方法中,方便区分同名的成员变量和局部变量
同名的静态变量和局部变量用类名来区分
同名的成员变量和局部变量用this来区分

int year;
 int month;
 int day;
 public MyDate(int year,int month) {
  this.year = year;
  this.month = month;
 }

2 用在构造方法中第一种,同上,可以用来区分同名的局部变量和成员变量

int year;
 int month;
 int day;
 public MyDate(int year,int month) {
  this.year = year;
  this.month = month;
 }

3 用在构造方法中第二种.用于重载调用当前类中的其他构造方法,提高代码重用性

public MyDate() {
  //this.year = 1970;
  //this.month = 1;
  //this.day = 1;
  
  this(1970,1,1);
 }
 public MyDate(int year,int month,int day) {
  //重载调用当前类中其他构造方法,只能出现在构造方法第一行
  this(year,month);
  this.year = year;
  this.month = month;
  this.day = day;
  System.out.println("-------");
 }

4 return this;可以返回当前对象的内存地址,做到链式调用
this用在构造方法中,可以重载调用当前类中其他构造方法,提高代码重用性

public class This_01 {
 	static int a = 1;
	 int b = 2;
	 public This_01 m2() {
 		 int b = 1;
		System.out.println(this.b);
		  return this;
	 }
 }

语法
this(参数);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值