Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...