Using “this” with methods (in Java)

前端 未结 7 1989
终归单人心
终归单人心 2020-12-08 16:12

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

7条回答
  •  无人及你
    2020-12-08 16:53

    Three obvious situations where you need it:

    • Calling another constructor in the same class as the first part of your constructor
    • Differentiating between a local variable and an instance variable (whether in the constructor or any other method)
    • Passing a reference to the current object to another method

    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;
        }
    }
    

    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 :)

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

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

    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.

提交回复
热议问题