使用“这个"带方法(在 Java 中) [英] Using "this" with methods (in Java)

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

问题描述

在 Java 方法中使用this"怎么样?它是可选的还是在某些情况下必须使用它?

what about using "this" with methods in Java? Is it optional or there are situations when one needs to use it obligatory?

我遇到的唯一情况是在类中调用方法中的方法.但它是可选的.这是一个愚蠢的例子,只是为了说明我的意思:

The only situation I have encountered is when in the class you invoke a method within a method. But it is optional. Here is a silly example just to show what I mean:

public class Test {

    String s;

    private String hey() {
        return s;
    }

    public String getS(){
        String sm = this.hey();
        // here I could just write hey(); without this
        return sm;
    }
}

推荐答案

您需要它的三种明显情况:

Three obvious situations where you need it:

  • 在与构造函数的第一部分相同的类中调用另一个构造函数
  • 区分局部变量和实例变量(无论是在构造函数中还是在任何其他方法中)
  • 将当前对象的引用传递给另一个方法

以下是所有三个的示例:

Here's an example of all three:

public class Test
{
    int x;

    public Test(int x)
    {
        this.x = x;
    }

    public Test()
    {
        this(10);
    }

    public void foo()
    {
        Helper.doSomethingWith(this);
    }

    public void setX(int x)
    {
        this.x = x;
    }
}

我相信也有一些使用内部类的奇怪情况,你需要 super.this.x 但应该避免它们,因为它们非常晦涩,IMO :)

I believe there are also some weird situations using inner classes where you need super.this.x but they should be avoided as hugely obscure, IMO :)

我想不出任何例子,为什么你会想要一个直接的 this.foo() 方法调用.

I can't think of any examples why you'd want it for a straight this.foo() method call.

saua 就模糊的内部类示例做出了贡献:

saua contributed this on the matter of obscure inner class examples:

我认为模糊的情况是:OuterClass.this.foo() 当访问外部的 foo() 时来自内部类中的代码的类,该类也具有 foo() 方法.

I think the obscure case is: OuterClass.this.foo() when accessing foo() of the outer class from the code in an Inner class that has a foo() method as well.

这篇关于使用“这个"带方法(在 Java 中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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