Java this
关键字
原文:https://www.studytonight.com/java/this-keyword-in-java.php
在 Java 中, this
关键字用来指代一个类的当前对象。我们可以用它来指代班上的任何一个成员。这意味着我们可以通过使用 this
关键字来访问任何实例变量和方法。
使用this
关键字的主要目的是解决当我们有相同的变量名例如实例和局部变量时的混乱。
我们可以将this
关键字用于以下目的。
this
关键字是用来指代当前对象的。this
始终是对调用方法的对象的引用。this
可以用来调用当前的类构造器。this
可以作为参数传递给另一个方法。
让我们首先了解this
关键字的最一般用法。正如我们所说的,它可以用来区分类中的局部变量和实例变量。
示例:
In this example, we have three instance variables and a constructor that have three parameters with same name as instance variables. Now, we will use this to assign values of parameters to instance variables.
class Demo
{
Double width, height, depth;
Demo (double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
public static void main(String[] args) {
Demo d = new Demo(10,20,30);
System.out.println("width = "+d.width);
System.out.println("height = "+d.height);
System.out.println("depth = "+d.depth);
}
}
宽度= 10.0 高度= 20.0 深度= 30.0
这里这个用来初始化当前对象的成员。例如, this.width 指的是当前对象的变量, width 只指在构造器中接收的参数,即调用构造器时传递的参数。
使用此关键字调用构造器
我们可以使用this
关键字从另一个函数内部调用构造器
示例:
在本例中,我们使用 this 关键字和参数从非参数化构造器调用参数化构造器。
class Demo
{
Demo ()
{
// Calling constructor
this("Studytonight");
}
Demo(String str){
System.out.println(str);
}
public static void main(String[] args) {
Demo d = new Demo();
}
}
今晚学习
使用此关键字访问方法
这是这个允许访问方法的关键字的另一种用法。我们也可以使用对象引用来访问方法,但是如果我们想使用 Java 提供的隐式对象,那么就使用this
关键字。
示例:
在这个例子中,我们使用这个来访问 getName()方法,它的工作原理和对象引用一样。见下面的例子
class Demo
{
public void getName()
{
System.out.println("Studytonight");
}
public void display()
{
this.getName();
}
public static void main(String[] args) {
Demo d = new Demo();
d.display();
}
}
今晚学习
从方法返回当前对象
在这种情况下,当我们想从一个方法返回当前对象时,我们可以用它来解决这个问题。
示例:
在这个例子中,我们创建了一个返回演示类对象的方法显示。为了返回对象,我们使用了this
关键字,并将返回的对象存储到 Demo 类型引用变量中。我们使用返回的对象来调用 getName()方法,它工作正常。
class Demo
{
public void getName()
{
System.out.println("Studytonight");
}
public Demo display()
{
// return current object
return this;
}
public static void main(String[] args) {
Demo d = new Demo();
Demo d1 = d.display();
d1.getName();
}
}
今晚学习