Java中的构造函数链接的重点是什么,以及如何将它与tostring()结合使用? [英] What is the point of constructor chaining in java and how to combine it with tostring()?

查看:144
本文介绍了Java中的构造函数链接的重点是什么,以及如何将它与tostring()结合使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道如何使用它,它是如何工作的.这个问题在现实生活中的意义是什么? 想象一下创建的类没有覆盖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 ??

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

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");

并尝试打印

System.out.println(constructorChaining);

我如何为此实现toString()

推荐答案

只需使用基于您调用的构造函数设置不同的字段来完成此操作:

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

这篇关于Java中的构造函数链接的重点是什么,以及如何将它与tostring()结合使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆