Java defining or initializing attributes of a class

前端 未结 3 1632
生来不讨喜
生来不讨喜 2021-02-05 06:35

Is there a difference between defining class attributes and initializing them? Are there cases where you want to do one over the other?

Exampl

3条回答
  •  礼貌的吻别
    2021-02-05 06:54

    Firstly you cannot set a primitive to be null as a primitive is just data where null is an object reference. If you tried to compile int i = null you would get a incompatible types error.

    Secondly initializing the variables to null or 0 when declaring them in the class is redundant as in Java, primitives default to 0 (or false) and object references default to null. This is not the case for local variables however, if you tried the below you would get an initialization error at compile time

     public static void main(String[] args)
     {
         int i;
         System.out.print(i);
     }
    

    Explicitly initializing them to a default value of 0 or false or null is pointless but you might want to set them to another default value then you can create a constructor that has the default values for example

    public MyClass
    {
       int theDate = 9;
       String day = "Tuesday";
    
       // This would return the default values of the class
       public MyClass()
       {
       }
    
       // Where as this would return the new String
       public MyClass (String aDiffDay)
       {
          day = aDiffDay;
       }
    }
    

提交回复
热议问题