Welcome to the Ranch
I am going to disagree with everybody; I have three things I believe about construcotrs.
1: You must write a constructor for every class you write. Otherwise the compiler will add a default constructor which might not be what you want.2: Every constructor must initialise every field in the class (directly or indirectly) to a consistent value. As a rule of thumb, regard anything allowing nulls as a mistake until proven otherwise.3: You should provide as few constructors as possible.If you provide two constructors, you are providing code two ways to instantiate your object. The mre ways you have to instantiate things, the more scope there is for something going wrong. Look at my Kettle class; all the field names should be obvious except minFill which means the least amount of
water to cover the element:-
That is a sole constructor; there is no chance of creating a kettle without providing those three pieces of data. You can enhance that constructor to refuse wrong arguments, e.g. negative capacity. Two of the fields are initialised to default values; every new kettle contains no water and is at room temperature, although those values will change as soon as you try to take it home (especially in Winter
). Note the idiom with this.make. That means that the field called make is on the left of the = operator and the local variable or parameter of the same name is on the right. I believe that is what a constructor should look like. And never use the keyword this in a constructor in any form other than that shown above. Only ever call methods from the constructor which are marked private or final.
CB is right to complain about the field names i j k. Especially if they are doubles; i j k should be reserved for ints.
You will doubtless have been taught that constructors are there to permit creation of objects. What you probably have not be told is that constructors are there to restrict creation of objects. You write one constructor, which means, “You can create objects my way, or not at all.”