在Java中,this和this()都是完全不同的。
this
关键字用来指代当前对象,即通过它来调用方法。this()
是用来从同一类别的另一个构造函数中调用一个构造函数。
下表显示了this
关键字和this()
之间点对点的区别。
this | this() |
---|---|
this 关键字只用于对象。this 指的是当前对象。 |
this() 只用于构造函数。 |
它指的是同一类的构造函数 | 其参数与传递给this(参数) 的参数一致。 |
Dot(.)操作符用于访问成员。例如,this.variableName; |
没有使用Dot(.)操作符。只有匹配的参数被传递。 |
this 关键字用于区分方法中的局部变量和实例变量。 |
this() 被用来指代属于同一类别的构造函数。 |
请看下面的代码,它描述了对this
个关键字的使用。
import java.io.*;
public class Student {
private String name;
private int age;
public Student(String name, int age)
{
this.name = name;
this.age = age;
}
public void show()
{
System.out.println("Name = " + this.name);
System.out.println("Age = " + this.age);
}
public static void main(String[] args)
{
// Creating new instance of Student Class
Student student = new Student("Yiibai", 23);
student.show();
}
}
运行结果:
Name = Yiibai
Age = 23
现在看一下下面的代码,它描述了this()
的使用。
import java.io.*;
public class Student {
private String name;
private int age;
// Constructor 1 with String as parameter.
public Student(String name)
{
// This line of code calls the second constructor.
this(23);
System.out.println("Name of Student : " + name);
}
// Constructor 2 with int in parameter.
public Student(int age)
{
System.out.println("Age of student = " + age);
}
// Constructor 3 with no parameters.
public Student()
{
// This line calls the first constructor.
this("Yiibai.com");
}
public static void main(String[] args)
{
// This calls the third constructor.
Student student = new Student();
}
}
运行结果:
Age of student = 23
Name of Student : Yiibai.com
请注意,
this()
应该始终是构造函数中的第一个可执行语句。否则,程序会在编译时出错。
| ——- | ——- | ——- |