使用“这个” java中的关键字 [英] Use of "this" keyword in java

查看:156
本文介绍了使用“这个” java中的关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当ai遇到这个关键字时,我正在研究Java中的方法覆盖。在互联网和其他来源上搜索了很多这个之后,我得出结论,当实例变量的名称与构造函数
相同时,使用 this 关键字。参数。我是对还是错?

I was studying method overriding in Java when ai came across the this keyword. After searching much about this on the Internet and other sources, I concluded that thethis keyword is used when the name of an instance variables is same to the constructor function parameters. Am I right or wrong?

推荐答案

这个是别名还是实例中当前实例的名称。它有助于消除本地变量(包括参数)的实例变量,但它本身可以用来简单地引用成员变量和方法,调用其他构造函数重载,或者只是引用实例。适用的一些例子(不详尽):

this is an alias or a name for the current instance inside the instance. It is useful for disambiguating instance variables from locals (including parameters), but it can be used by itself to simply refer to member variables and methods, invoke other constructor overloads, or simply to refer to the instance. Some examples of applicable uses (not exhaustive):

class Foo
{
     private int bar; 

     public Foo() {
          this(42); // invoke parameterized constructor
     }

     public Foo(int bar) {
         this.bar = bar; // disambiguate 
     }

     public void frob() {
          this.baz(); // used "just because"
     }

     private void baz() {
          System.out.println("whatever");
     }

}

这篇关于使用“这个” java中的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆