The use of “this” in Java

后端 未结 13 1953
-上瘾入骨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:58

    If you don't write "this.variable" in your constructor, and if you have a local variable (including the function parameter) with the same name as your field variable in the constructor, then the local variable will be considered; the local variable shadows the field (aka class variable).

    One place where "this" is the only way to go:

    class OuterClass {
      int field;
    
      class InnerClass {
        int field;
    
        void modifyOuterClassField()
        {
          this.field = 10; // Modifies the field variable of "InnerClass"
          OuterClass.this.field = 20; // Modifies the field variable of "OuterClass",
                                      // and this weird syntax is the only way.
        }
      }
    }
    

提交回复
热议问题