Advantages of Constructor Overloading

前端 未结 6 1819
青春惊慌失措
青春惊慌失措 2021-01-18 10:45

I am very new to Java and trying to learn the subject, having previous programming exposure in only HTML/CSS. I have started with Herbert Schildt and progressed through a fe

6条回答
  •  太阳男子
    2021-01-18 11:50

    The way the constructor is defined will make sure that the parameters of the constructor will be passed to the object upon instantiation.

    Overloading a method won't "force" anyone to call it unlike having parameters in the constructor, where you can't instanciate an object without passing those paremeters.

    Having multiple way to construct an object might be useful, like with the Color class, in ndj's answer, can be created in four different ways. Each way makes sure that Color as the minimum informations to be useful, or "work".

    Those informations could be missing if Color only had a contructor without parameter and, for the class to "work", would be to call setRand the other methods... which don't exist in the Color class .

提交回复
热议问题