Could 'this' be omitted when calling a method in Java?

I have a silly question about Java grammar (6/7/8) - are these two method call snippets always equivalent?

  • from this

    this.myMethod(4);
    
          

  • without this

    myMethod(4);
    
          

Note. Of course the problem lies in every number, type and combination of arguments

Weaker instruction: given a program P

, can I create a program P'

only by deleting this.

before each method call?

I've taken into account local classes, anonymous classes, inner classes and various inheritance, but couldn't find a contradiction. So I believe that both snippets are actually the same. Unfortunately, I cannot find any suitable proof (e.g. from the official grammar).

Could you please prove that I am wrong as a result of a contradiction, or give me some hints for constructing an equivalence proof? Many thanks.

EDIT: Equivalence has not been proven correctly (see comments below). What about the weaker statement ?

+3


source to share


2 answers


The Java Language Specification contains

  • If the form MethodName

    is - that is, simply Identifier

    - then:
    • Otherwise, let T

      is the declaring type declaration of which this method is a member, and let n be an integer such that T

      is the n'th lexically encompassing type declaration of the class whose declaration immediately contains a method call. Target link is the nth lexically enclosing instance this

      .

and

When used as a primary expression, a keyword this

denotes a value that is a reference to the object for which the instance method was either invoked by the default method (ยง15.12) or to the object that is constructed



and

  • If the form has Primary . [TypeArguments] Identifier

    , then:
    • Otherwise, the Primary expression is evaluated and the result is used as the target link.

Primary

here referring to this.*

.

In both cases, the method will resolve to the same method. Given all this information, there is no compiled program P'

that can be created from a compiled program P

.

+2


source


There is at least one case where they are not equivalent. For example this code

void doStuff(){}
void test(){
    Runnable r = new Runnable(){
        @Override
        public void run(){
            doStuff();
        }
    };
    r.run()
}

      

Quite right, while



void doStuff(){}
void test(){
    Runnable r = new Runnable(){
        @Override
        public void run(){
            this.doStuff();
        }
    };
    r.run()
}

      

not.

Thus, if you have a method defined in a class, an anonymous object declared in that class can call its methods without using it this

, but if it does use it this

, it results in a compiler error (assuming it does not provide an implementation of the method name itself ).

+1


source







All Articles