java中的this关键字

一、this关键字的基础知识

1.this是一个关键字,翻译为这个
2.this是一个引用,是一个变量,保存了内存地址指向了自身,this存储再JVM堆内存Java对象的内部。
3.每个Java对象都有其对应的this
4.this可以出现在“实例方法”,this指当前正在执行任务的对象。(也可省略不写)
5.static的方法调用不需要对象,直接使用类名,所以执行过程中没有当前对象,所以不能使用this。
6.this用来区分局部变量和实例变量的时候不能省略。

例如:

public class CoustmerTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Coustmer c1=new Coustmer();
		c1.name="lisi";
		Coustmer c2=new Coustmer();
		c2.name="zhangsan";
	}

}
public class Coustmer {
	String name;
	public Coustmer() {
		//没有static关键字的方法被称为“实例方法”访问:“引用.”
		//没有static关键字的变量被称为“实例变量”
		//有对象的参与
		
	}
	public void Shopping() {
			System.out.println(name+"在购物");
		}
}

在这里插入图片描述

没有static关键字的方法被称为“实例方法”访问:“引用.”
没有static关键字的变量被称为“实例变量”
带有static关键字的方法访问时通过类名的方式进行访问的,没当前对象.
实例变量和实例方法都需要对象的存在。

7.可以使用在实例方法中代表当前对象【语法格式:this.】
8.可以在构造方法中通过当前的构造方法调用其他的构造方法【语法格式:this(实参)】,只能出现在第一行

例如:

package day10;

public class DateTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Date c1=new Date();
		c1.print();
		Date c2=new Date(2008,8,8);
		c2.print();
	}

}

package day10;

public class Date {
	private int year;
	private int month;
	private int day;
	
	//构造函数
	public Date(int year, int month, int day) {
		this.year = year;
		this.month = month;
		this.day = day;
	}
	public Date() {
//		this.year = 1970;
//		this.month = 1;
//		this.day = 1;
		//调用构造方法
		this(1970, 1, 1);
	}
	
	//Setter and getter函数
	public int getYear() {
		return year;
	}
	public void setYear(int year) {
		this.year = year;
	}
	public int getMonth() {
		return month;
	}
	public void setMonth(int month) {
		this.month = month;
	}
	public int getDay() {
		return day;
	}
	public void setDay(int day) {
		this.day = day;
	}
	public void print() {
		System.out.println(this.year+"年"+this.month+"月"+this.day+"日");
	}
	
}

package day10;

public class Test {
	public static void method1() {
		Test.dosome();
		dosome();
	}
	public void method2() {
		this.doother();
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//完整方式
		Test.method1();
		//省略方式
		method1();
		Test a=new Test();
		a.method2();
	}
	public static void dosome() {
		System.out.println("do some");
	}
	public void doother() {
		System.out.println("do other");
	}

}

在这里插入图片描述带有static的方法,可以采用类名的方式访问,也可以采用引用的方式访问,采用引用方式的时候和引用指向的对象无关。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值