栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java中的this关键字

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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的方法,可以采用类名的方式访问,也可以采用引用的方式访问,采用引用方式的时候和引用指向的对象无关。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/731903.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号