java 中的构造函数链接有何意义以及如何将其与 tostring() 结合使用?

What is the point of constructor chaining in java and how to combine it with tostring()?

所以我知道如何使用它,它如何 works.The 质疑在现实生活场景中有什么意义。 想象一下在没有 toString() 覆盖的情况下创建 class。那么如果不能正确显示,class 有什么意义呢??

请尽量不要解释构造函数链是如何工作的或类似的东西。 我知道它是如何工作的。我想知道现实生活中有人这样做吗 因为没有 toString() 覆盖我不明白这一点

   public class ConstructorChaining {

        String a;
        int b;
        int c;
        int d;
        int e;

        public ConstructorChaining() {
            this("");
        }


        public ConstructorChaining(String a) {
            this(a, 0);

        }

        public ConstructorChaining(String a, int b) {
            this(a, b, 0);

        }

        public ConstructorChaining(String a, int b, int c) {
            this(a, b, c, 0);

        }

        public ConstructorChaining(String a, int b, int c, int d) {
            this(a, b, c, d, 0);

        }

        public ConstructorChaining(String a, int b, int c, int d, int e) {
            this.a = a;
            this.b = b;
            this.c = c;
            this.d = d;
            this.e = e;
        }

    }

想象一下我创建了一个对象

ConstructorChaining constructorChaining=new ConstructorChaining("name");

并尝试打印它

System.out.println(constructorChaining);

我如何为此实现toString()

只需执行此操作,使用根据您调用的构造函数设置不同的字段:

public class ConstructorChaining {

   String a;
   int b;
  //This value is different for each constructor, so you can control your
  //toString implementation
  String asString;

public ConstructorChaining() {
            this("");
        }


        public ConstructorChaining(String a) {
            this(a, 0, a + "");

        }

        public ConstructorChaining(String a, int b) {
            this(a, b, 0, a + "" + b);

        }

        private ConstructorChaining(String a, int b, String asString) {
            this.a = a;
            this.b = b;
            this.asString = asString;
        }

@Override
public String toString() {
  return "Overriden toString, asString = " + asString;
}

 public class ConstructorChaining {

    String a;
    int b;
    int c;
    int d;
    int e;

    public ConstructorChaining() {
        this("");
    }


    public ConstructorChaining(String a) {
        this(a, 0);

    }

    public ConstructorChaining(String a, int b) {
        this(a, b, 0);

    }

    public ConstructorChaining(String a, int b, int c) {
        this(a, b, c, 0);

    }

    public ConstructorChaining(String a, int b, int c, int d) {
        this(a, b, c, d, 0);

    }

    public ConstructorChaining(String a, int b, int c, int d, int e) {
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
        this.e = e;
    }

    @Override 
    public String toString() {
        return "ConstructorChaining={a=" + a + ", b=" + b + ", c=" + c + ", d=" + d + ", e=" + e;
    }
}

看看你的朋友怎么说的,contractors和toString重写方法没有关系。

所有基本类型都已初始化为 0,因此您无需关心值是否存在。