有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我没有初始化变量,但仍然收到一个输出

这是我的密码:

class Xyz{
   public static void main(String args[])
   {
      first fobj = new first(10);
      for(int i=0;i<5;i++){
         fobj.add();
         System.out.printf("%s",fobj);
      }
   }
}

class first{
   public int sum=0;
   public final int num;
   first(int x){
      num=x;
   }

   public void add(){
      sum+=num;
   }

   public String toString()
   {
      return String.format("sum = %d" ,sum);
   }
}


output:
sum=10
sum=20
sum=30
sum=40
sum=50

在类first中,我没有初始化名为“sum”的变量,但仍然得到了输出。有人能给我解释一下吗? asgfafgalsdfkjsaflkasflaskfalskfajlskfaskfaskfaslkjflaskfaslkflasjkf


共 (3) 个答案

  1. # 1 楼答案

    类和实例数据成员会自动默认为其类型的所有位关闭值(0int的情况下),即使您没有显式地这样做。由于sum是一个实例数据成员,因此隐式默认为0

    以下是§4.12.5 of the Java Language Specification的内容:

    Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2):

    • For type byte, the default value is zero, that is, the value of (byte)0.
    • For type short, the default value is zero, that is, the value of (short)0.
    • For type int, the default value is zero, that is, 0.
    • For type long, the default value is zero, that is, 0L.
    • For type float, the default value is positive zero, that is, 0.0f.
    • For type double, the default value is positive zero, that is, 0.0d.
    • For type char, the default value is the null character, that is, '\u0000'.
    • For type boolean, the default value is false.
    • For all reference types (§4.3), the default value is null.
  2. # 2 楼答案

    实例成员自动初始化为默认值JLS-4.12.5 Initial Values of Variables

    Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):

    ...

    For type `int`, the default value is zero, that is, 0. 
    
  3. # 3 楼答案

    在Java中,所有成员变量都会在创建对象时自动初始化为默认值,即使您自己不这么做。int的默认值为0