不积跬步,无以至千里;不积小流,无以成江海。

 

Java语言基础

 

Java的 this 关键字

this关键字指向的是当前对象的引用。

三大作用:调用类的属性、方法、构造器和当前对象。

 

  • 调用类的属性:

没有使用this的情况

class Person{
	private String name;
	private int age;
	
	public Person(String name, int age){
		name = name;
		age = age;
	}	
	public String getInfo() {
		return "姓名:" + name + ",年龄:" + age;
	}
}

public class Test {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Person person = new Person("tutu", 24);
		System.out.print(person.getInfo());

	}
}

程序输出

姓名:null,年龄:0

结论:

没有正确将内容赋给属性;

此时,为了明确哪个是类中的属性,需要加上this.类中属性。

class Person{
	private String name;
	private int age;
	
	public Person(String name, int age){
		this.name = name;
		this.age = age;
	}	
	public String getInfo() {
		return "姓名:" + name + ",年龄:" + age;
	}
}

public class Test {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Person person = new Person("tutu", 24);
		System.out.print(person.getInfo());

	}
}

程序输出:

姓名:tutu,年龄:24

(通过构造方法为类中的属性赋值)

 

  • 调用构造方法
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 Test {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Person person = new Person("tutu", 24);
		System.out.print(person.getInfo());
	}
}

程序输出:

无参构造方法!
姓名:tutu,年龄:24

 

注意:

1)this()调用其他构造方法的语句只能放在构造方法(在其他普通方法里是不行的)的首行;

2)在使用this调用其他构造方法的时候,至少有一个构造方法是不用this调用的。(必须要有结尾,不能无限期的调用下去,循环递归调用);

3)其他普通方法不能调用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 void print(){
		System.out.println("~~~~~~~~~~~");
	}
	public String getInfo() {
		this.print();
		return "姓名:" + name + ",年龄:" + age;
	}
}

public class Test {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Person person = new Person("tutu", 24);
		System.out.print(person.getInfo());
	}
}

程序输出:

无参构造方法!
~~~~~~~~~~~
姓名:tutu,年龄:24

注意:这个this可以省略。

 

  • 调用当前对象
class Person{
	private String name;
	private int age;
	
	public Person() {
		System.out.println(this);
	}
	
}

public class Test {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Person person = new Person();
		System.out.print(person);
	}
}

程序输出:

Person@15db9742
Person@15db9742

结论:

用this调用的是当前对象。

 

博客借鉴:https://www.jb51.net/article/121103.htm

posted on 2019-11-25 16:24  smile学子  阅读(146)  评论(0编辑  收藏  举报