constructor(我们编写的)是否替换了默认构造函数?

huangapple go评论62阅读模式
英文:

Do constructor( that we code ) replaces the default constructor?

问题

public class A {
  int i;
  int j;

  A() {
    i = 3; // 我没有初始化j;
  }

  public static void main(String[] args) {
    A obj = new A();
    // 如果我的构造函数初始化了int j,为什么会打印出obj.j的值呢?
    System.out.println(obj.i + obj.j); 
  }
}

如果我们的自定义构造函数替换了默认构造函数,那么我在构造函数中没有初始化的引用值将如何获得默认值?
英文:
public class A {
  int i;
  int j;

  A() {
    i = 3; // I have not intialized j;
  }

  public static void main(String[] args) {
    A obj = new A();
    // Why obj.j is printed if my constructor had initialized int j?
    System.out.println(obj.i + obj.j); 
  }
}

if our coded constructor replaces the default constructor then how the reference values that I had not initialized in my constructor get default values

答案1

得分: 2

所有实例变量都有默认值,无论是否有任何构造函数对它们进行初始化。所有数值原始实例变量的默认值为0,这就是您代码中的j的值(即使您尚未初始化它)。

英文:

All instance variables have default values, regardless of whether any constructor initializes them. All numeric primitive instance variables have a default value of 0, which is the value of j in your code (even though you haven't initialized it).

huangapple
  • 本文由 发表于 2020年8月5日 16:23:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63261176.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定