在Java中this关键字
时间:2020-02-23 14:35:37 来源:igfitidea点击:
Java中的 this关键字用于指代当前对象或者类实例。
它可以在构造函数中使用,调用任何其他重载的构造函数,但 this关键字应该是构造函数中的第一个语句。
this关键字可以用于实例变量
this关键字可用于指代类的实例变量。
package org.igi.theitroad; public class Employee { String name; int age; public Employee(String name,int age) { this.name=name; this.age=age; } public void workOnAssignment() { //Working on assignment } 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 static void main(String args[]) { Employee e1=new Employee("John",20); System.out.println("Employee's name : "+e1.getName()); System.out.println("Employee's age : "+e1.getAge()); } }
运行上面的程序时,我们将得到以下输出:
Employee's name : John Employee's age : 20
正如我们所看到的,我们使用 this关键字在构造函数中使用 this关键字设置实例变量的值。
this关键字可用于调用重载的构造函数
如果要调用同一类的重载(overloading)构造函数,则可以使用 this关键字来执行此操作。
例如:
package org.igi.theitroad; public class Employee { String name; int age; public Employee() { System.out.println("Calling No arg constructor"); } public Employee(String name,int age) { this(); System.out.println("Calling Parameterized constructor"); this.name=name; this.age=age; } public void workOnAssignment() { //Working on assignment } 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 static void main(String args[]) { Employee e1=new Employee("John",20); System.out.println("Employee's name : "+e1.getName()); System.out.println("Employee's age : "+e1.getAge()); } }
请注意,用于调用另一个构造函数的this关键字应该是该构造函数中的第一个语句。
this关键字可以使用类的返回对象
package org.igi.theitroad; public class Employee { String name; int age; public Employee(String name,int age) { this.name=name; this.age=age; } public void workOnAssignment() { //Working on assignment } 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 Employee getEmployee() { return this; } public static void main(String args[]) { Employee e1=new Employee("John",20); Employee e1Copy=e1.getEmployee(); System.out.println("Employee's name : "+e1Copy.getName()); System.out.println("Employee's age : "+e1Copy.getAge()); } }