The use of “this” in Java

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

    What you are experiencing is called variable shadowing. Have a look at this overview for different kinds of variables in Java.

    Generally speaking: The Java compiler uses the nearest variable it can find for an assignment. In a method it will first try to find a local variable and then enlarge the focus of its search to class and instance variables.

    One habit I personally find good (others don't like it) is prefixing a member variable with m_ and using uppercase for CONSTANT_VARIABLES that don't change their value. Code where variable shadowing is used on purpose is very(!) difficult to debug and work with.

提交回复
热议问题