Java this关键字

Java this关键字教程

Java 语言 中,this 关键字是比较难理解的,它的语法比较灵活。this 关键字可以表示强调调用的是本类中的方法,类中的属性,可以用 this 调用本类的构造方法,this 还可以表示当前的对象。

Java this详解

语法

this.属性,方法名。。。

参数

参数 描述
this 使用 this 的关键字
. 使用 this 的时候后面需要加 . ,. 的后面追加相关信息。比如:方法,属性,构造方法和当前对象等等

说明

this 可以理解成当前的对象,它可以使用当前对象中的属性,方法和构造函数等等。

案例

我们先定义一个案例用到的公共类,Person 类,表示人相关信息,里面定义了姓名和年龄,定义了一个 构造方法 来给属性赋值。

package com.haicoder.net.haithis; public class Person { //年龄 private Integer age; //姓名 private String name; public Person() { System.out.println("构造方法打印:" + "嗨客网(www.haicoder.net)"); } public Person(Integer age, String name) { this(); this.age = age; this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

this调用本类中的属性

package com.haicoder.net.haithis; public class ThisTest { public static void main(String[] args) { System.out.println("嗨客网(www.haicoder.net)"); Person person = new Person(20, "嗨客网"); System.out.println("姓名为:" + person.getName()); System.out.println("年龄为:" + person.getAge()); } }

运行结果如下:

24 this调用属性.png

Person 类里面的构造方法用了 this.name 和 this.age 给 类里面的 name 和 age 两个属性[替换成链接 02 类与对象] 进行赋值。我们可以把类里面定义的 name 和 age 理解为属性,而构造方法里面,也定义了相同的名字,构造方法里面的叫参数。

类里面的 name 和 age 与构造方法里面的 name 和 age 一样的名称,如果不加 this 那么是很容易混淆的,不知道使用的是哪个里面对应的 name 和 age,而加了 this 之后,就明确了是当前类里面的属性。

this调用构造方法

如果一个类中有多个构造方法,也可以使用 this 关键字进行互相调用的。

我们定义一个场景,就是只要调用一个类的构造函数的时候,就打印出 嗨客网(www.haicoder.net),无论你调用类里面的什么构造函数。我们在类 Person 里面定义了两个构造函数,一个有参,一个无参。

package com.haicoder.net.haithis; public class ThisTest { public static void main(String[] args) { System.out.println("嗨客网(www.haicoder.net)"); Person noArgsPerson = new Person(); Person person = new Person(20, "嗨客网"); } }

运行结果如下:

25 this调用构造函数.png

我们调用了一个无参的构造函数,调用了传递两个参数的构造函数。根据运行结果我们可以看到,两次都将需要打印的信息打印出来了。在有参数的构造方法中,我们调用了 this() 方法,就相当于调用了当前类的无参构造函数,就可以调用里面的打印方法,而不需要在每个构造方法里面都写一遍打印。我们可以举一反三,如果调用的构造函数里面有多个参数,我们可以在 this(参数1,参数2…)。将对应的类型赋值就行。

在使用 this() 的时候,我们需要注意一点,在类的所有方法中,只有构造方法是被优先调用的,所以使用 this 调用构造方法必须也只能放在构造方法的首行。

this表示当前对象

在上面的例子中,我们看到了类里面对属性进行赋值的时候,在构造方法赋值的时候,都使用了 this 的关键字。这些 this 表示什么呢?表示当前的对象。

package com.haicoder.net.haithis; public class ThisTest { public static void main(String[] args) { System.out.println("嗨客网(www.haicoder.net)"); Person haicoder = new Person(21,"嗨客"); System.out.println(haicoder.getName() + " : " + haicoder.getName()); Person noodles = new Person(20, "面条小子"); System.out.println(noodles.getName() + " : " + noodles.getAge()); } }

26 this表示当前对象.png

我们看到例子中,我们定义了两个对象,一个是 haicoder 一个是 noddles 。在调用构造方法的时候,构造方法里面使用了 this 关键字进行赋值,所以,我们看到打印 haicoder 里面和 noodles 里面的属性的时候,值是不相同的,他们不相互影响。

this关键字总结

Java 语言中,this 关键字是比较特殊的,比较难以理解的,它可以表示当前对象,可以调用当前类里面的属性和方法,也可以调用本类里面的构造方法。这个我们可以将上面例子了解,然后在实践中慢慢的消化。