开发者

Assining values to class variables

开发者 https://www.devze.com 2023-04-13 07:19 出处:网络
I\'ll try to keep this simple.开发者_开发百科 class MyClass { private int x = 3; } vs. class MyClass {

I'll try to keep this simple.

开发者_开发百科
class MyClass {
   private int x = 3;
}

vs.

class MyClass {
   private int x;
   public MyClass() {
      x = 3;
   }
}

What's the difference between the two and how do these differences come into play?

Thanks in advance.


class MyClass {    
   private int x = 3; 
} 

is same as

class MyClass {    
   private int x; 
   MyClass() { // default constructor based on the class access modifier
     x = 3; 
   }
} 


These are both the same But if x were a static variable, they would be different.


Nothing at all. Variable's are set when a constructor is called, you can see this by adding the line MyClass temp = new MyClass() and stepping into it with the debugger, the debugger will go to the line private int x = 3; first.


Initialization of fields are done before constructor is called. But for your example they are same


In your example you actually have instance variable, not the class variable. Difference comes in the moment when you add new constructor MyClass(Object argument) and forget to set x directly and forget to call original no-arg constructor as well. Making it final, if applicable, will of course force you to remember to set value somewhere.

In the case of class variable things get much more interesting, just change x to static and add following main method to the MyClass and observe results.

   public static void main(String ... args) {
       MyClass y = null;
       System.out.println(y.x);
       System.out.println(MyClass.x);
       new MyClass();
       System.out.println(MyClass.x);
   }


As others has mentioned they both are equivalent. The main difference is the readability, duplicity and maintainability of the code. If we expand the given example to have more than one constructor you'll start to notice differences. If the value of x is not to depend on the constructor I'd recommend to initialize the field variable else set the value in the constructors. This will somewhat increase the readability and maintainability of the code and remove duplicated code (in the case were several constructors are to initiate the variable with the same value).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号