编程语言
首页 > 编程语言> > 在Java中调用方法时可以省略“ this”吗?

在Java中调用方法时可以省略“ this”吗?

作者:互联网

我对Java(6/7/8)语法有一个愚蠢的问题-这两个方法调用片段是否总是等效的?

>与此

this.myMethod(4);

>没有这个

myMethod(4);

注意:当然,问题在于参数的每个数字,类型和组合

较弱的说法:给定程序P,我只能删除该程序才能创建程序P’.在每个方法调用的前面?

我已经考虑了本地类,匿名类,内部类和各种继承,但可能没有发现任何矛盾.因此,我相信两个片段实际上都是相同的.不幸的是,我无法找到任何合适的证明(例如,从官方语法中).

您能通过矛盾证明我错了吗,还是给我一些构造等效证明的线索?非常感谢.

编辑:证明等价是错误的(请参见下面的评论)较弱的语句呢?

解决方法:

Java Language Specification个州

  • If the form is MethodName – that is, just an Identifier – then:
    • Otherwise, let T be the enclosing type declaration of which the method is a member, and let n be an integer such that T is the n’th
      lexically enclosing type declaration of the class whose declaration
      immediately contains the method invocation. The target reference is
      the n’th lexically enclosing instance of this.

When used as a primary expression, the keyword this denotes a value
that is a reference to the object for which the instance method or
default method was invoked (§15.12), or to the object being
constructed

  • If the form is Primary . [TypeArguments] Identifier involved, then:
    • Otherwise, the Primary expression is evaluated and the result is used as the target reference.

这里主要指此.*.

在两种情况下,该方法都将解析为相同的方法.
给定所有这些信息,就没有可以从可编译程序P创建的可编译程序P’.

标签:invoke,this,grammar,java,methods
来源: https://codeday.me/bug/20191121/2050138.html