javaconstructorconstructor-chaining

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


So i know how to use it, how it works.The question what is the point in real life scenario. Imagine created class without toString() overriding. So what is the point in that class if you can't display it properly ??

And please try not to explain how constructor chaining works or something like that. I know how it works. I want to know does anyone do this in real life because without toString() overriding i don't see the point

   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;
        }

    }

so imagine i created an object

ConstructorChaining constructorChaining=new ConstructorChaining("name");

and tried to print it

System.out.println(constructorChaining);

How do i implement toString() for this


Solution

  • Just do this, using a field that is set differently based on the constructor you called:

    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;
    }