Java nested constructors

snotnose

Ars Tribunus Militum
2,747
Subscriptor
My main constructor does stuff, my 'helper' (sorry, not up on OO terminology) constructors call the main constructor with various defaults:
Code:
public class Broken {
        private int foo;

        Broken() {
            Broken(0);        // Gives 'error: cannot find symbol'
            this.Broken(1); // Ditto
        }
        Broken(int bar) {
            foo = bar;
        }

        private void show(String why) {
            System.out.println(why + foo);
        }

    public static void main(String[] args) {
        Broken b = new Broken();
        Broken b2 = new Broken(42);

        b.show("broken() ");
        b2.show("broken(42) ");
    }
}
Is this forbidden, or am I missing some syntactical sugar?
 

ShuggyCoUk

Ars Tribunus Angusticlavius
9,975
Subscriptor++
Also, from a discoverability point of view, sometimes it's better to have a bunch of static methods (often termed factories, but there's no need to put that in the name) with Reasonable names indicating the intent. e.g.
Java:
// this could be private if you like, but there's no need)
class Rectangle {
    public final double Height;
    public final double Length;

    public Rectangle(double height, double length) {
        this.Height = height;
        this.Length = length;
    }
    
    public static Rectangle Square(double side) {
        return new Rectangle(side, side);
    }
    
    private static final double GoldenRatio = 1.0 + Math.sqrt(5.0)) / 2;   
    
    public static Rectangle GoldenRatioFromSmallHeight(double height) {
        return new Rectangle(height, height * GoldenRatio);
    }
    
    public static Rectangle GoldenRatioFromSmallLength(double length) {
        return new Rectangle(length * GoldenRatio, length);
    }   
}
I spent 30 seconds giving thought to the names there, likely that could be improved but you get the idea.
These work well when the types of the parameters are insufficient to indicate intent well.