Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Martin Gregorie Newsgroups: comp.lang.java.programmer Subject: Re: How to assign an object to another in it method? Date: Mon, 3 Jul 2017 10:59:12 -0000 (UTC) Organization: A noiseless patient Spider Lines: 73 Message-ID: References: <46334961-cc18-491f-828c-32e7401c7832@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Injection-Date: Mon, 3 Jul 2017 10:59:12 -0000 (UTC) Injection-Info: mx02.eternal-september.org; posting-host="c38faa1fa99f0be03b23f52420ce2346"; logging-data="17061"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19PoK+Uxr7h0/+66B8n3s0H9U0Rp/DIVuA=" User-Agent: Pan/0.141 (Tarzan's Death; 168b179 git.gnome.org/pan2) Cancel-Lock: sha1:xFVhxxvLOt7btvOFOYBzQetzBfk= Xref: csiph.com comp.lang.java.programmer:36793 On Sun, 02 Jul 2017 21:23:26 -0400, Arne Vajhøj wrote: > On 6/28/2017 8:51 AM, Eric Douglas wrote: >> On Wednesday, June 28, 2017 at 8:24:54 AM UTC-4, Andreas Leitgeb wrote: >>> Obviously, stuff shouldn't be exactly duplicated in multiple c'tor >>> bodies, and doesn't need to, either, for reasons stated. >> >> public class MyClass String var1; >> public MyClass(){ >> this("init"); >> } >> public MyClass(final String arg){ >> var1=arg; >> } >> >> >> Normally it's like this. Now if you were to put something in the no >> arg constructor and something calls this one arg constructor with a >> super(), that gets missed. I can't think of a case where you would >> want 2 constructors doing something totally different that shouldn't >> actually be 2 different classes. > > > The above is one reason - which is really the issue of Java formal > parameters not supporting default values. > > But there are other reasons. One that comes to my mind is different > input types carrying the same information. > > String(String original) > String(char[] value) > String(byte[] bytes, String charsetName) > etc. > > comes to mind. > > Of course those are also tightly related. > > Arne In practise, I often find myself doing something like this: public class Demo { private String name; private int number; private boolean prisoner; public Demo(String name, int answer, boolean prisoner) { this.name = name; this.number = number; this.isPrisoner = prisoner; } public Demo(String name) { super(name, 6, true); } } ... and so on. IOW there's one constructor that can set all attributes that might be set externally and a number of others that accept fewer arguments and set appropriate defaults for the other attributes. -- martin@ | Martin Gregorie gregorie. | Essex, UK org |