The use of “this” in Java

后端 未结 13 1975
-上瘾入骨i
-上瘾入骨i 2020-12-09 21:58

If I write the following class:

public class Example {

      int j;
      int k;

      public Example(int j, int k) {
           j = j;
           k = k;
          


        
13条回答
  •  误落风尘
    2020-12-09 22:51

    To answer your follow-up question about this with method, the inner class mentioned by Srikanth is still a valid example of using this: (with method this time)

    public class OuterClass
    {
        void f() {System.out.println("Outer f()");};
        class InnerClass {
            void f() {
                System.out.println("Inner f()");
                OuterClass.this.f();
            }
        }
    }
    

    You have the same situation with anonymous class:

    You can refer to the outer class’s methods by:

    • MyOuterClass.this.yOuterInstanceMethod(),
    • MyOuterClass.myOuterInstanceMethod(),
    • or simply myOuterInstanceMethod() if there is no ambiguity.

提交回复
热议问题