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

全面理解Java中this关键字

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

全面理解Java中this关键字

this是什么?

在java中,this关键字比较难理解,它的作用及其词义很接近。
1.当它在方法内部使用时,即这个方法所属对象的引用;
2.当它在个构造器内部使用时,表示个该构造器正在初始化的对象;

this关键字可以调用类的属性、方法和构造器

什么时候使用this关键字呢?
1.当在方法内需要用到调用该方法的对象时,就用this。
具体的:我们可以用this来区分属性和局部变量。比如:this.name=name;

使用this调用属性、方法

class Person{
	private String name;
	private int age;
	public Person(String name,int age){
		this.name = name;
		this.age = age;
	}
	public void getInfo(){
		System.out,println("姓名:" + name);
		this.speak();   //可省略this关键字
	}
	public void speak(){
		System.out.println("年龄:"+ this.age);
	}
}
public class PersonTest{
	public static void main(String[] args){
		Person per = new Person("吴俊",23);
		person.getInfo();
	}
}

小总结:
1.在任意方法和构造器内,如果使用当前类的成员变量过成员方法可以在其前面添加this,增加程序的阅读性。不过,通常我们都习惯性省略this
2.当形参与成员变量同名时,如果在方法内或构造器内需要使用成员变量,必须添加this关键字来表明该变量是类的成员变量
3.使用this关键字访问属性和方法时,如果在本类中未找到,会从父类中查找。

使用this调用本类的构造器

class  Person{
	private String name;
	private int age;
	public Person(){ //无参构造器
		System.out.println("新对象实例化");
	}
	public Person(String name){
		this();  //调用本类中的无参构造器
		this.name = name;
	}
	public Person(String name,int age){
		this(name);
		this.age = age;
	}
	public String getInfo(){
		return "姓名:"+name+",年龄"+age;
	}
}

public class PersonTest{
	public static void main(String[] args){
		Person per = new Person("吴俊",23);
		person.getInfo();
	}
}

4.this可以作为一个类中构造器相互调用的特殊格式

注意

可以在类的构造器中使用“this(形参列表)”的方式,调用本类中重载的其它构造器!要明确:构造器中不能通过“this(形参列表)“的方式调用自身构造器如果一个类中声明了n个构造器,则最多有n-1个构造器中使用了“this(形参列表)”“this(形参列表)”必须声明在类的构造器的首行!在类的一个构造器中,最多中只能声明一个”this(形参列表)”

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

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

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