Java this 关键字
本文介绍 Java this 关键字的作用。
总的来说,Java this 关键字有如下三个特征:
1. 表示类中的属性和调用方法;
2. 调用本类中的构造方法;
3. 表示当前对象;
下面根据具体代码说明。
1. 表示类中的属性和调用方法,代码:
package hello; class People1{ private String name; private int age; public People1(String name, int age){ this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void tell(){ System.out.println("姓名:"+ this.getName() + " " + "年龄: " + this.getAge()); } } public class DemoMethod { public static void main(String[] args) { People1 p = new People1("张三", 30); p.tell(); } }
在上述代码中,用到了两次 this,分别是
this.name = name; this.age = age;
和
System.out.println("姓名:"+ this.getName() + " " + "年龄: " + this.getAge());
第一处的 this 表示了类中的属性,第二处的 this 表示了类的调用方法。
2. 调用本类中的调用方法,代码:
package hello; class People1{ private String name; private int age; public People1(String name, int age){ this(); this.name = name; this.age = age; } public People1(){ System.out.println("无参数的构造方法"); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void tell(){ System.out.println("姓名:"+ this.getName() + " " + "年龄: " + this.getAge()); } } public class DemoMethod { public static void main(String[] args) { People1 p = new People1("张三", 30); p.tell(); } }
程序输出:
无参数的构造方法 姓名:张三 年龄: 30
在 People1 中定义了无参数的构造方法,我们可以通过 this() 调用它,需要注意的是,必须要在程序的第一行调用 this()
3. 表示当前对象,代码如下:
package hello; class People1{ private String name; private int age; public People1(String name, int age){ this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void tell(){ System.out.println(this); } } public class DemoMethod { public static void main(String[] args) { People1 p = new People1("张三", 30); System.out.println(p); p.tell(); } }
程序输出:
hello.People1@677327b6 hello.People1@677327b6
可以看出程序输出的对象信息都是一致的。