Advantages of Constructor Overloading

前端 未结 6 1816
青春惊慌失措
青春惊慌失措 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:33

    It depends completely on how you are constructing your object.

    One of Classical example of Constructor overloading is ArrayList in Java. ArrayList has three constructors one is empty, other takes a collection object and one take initial Capacity. these overloaded constructor allows flexibility while create arraylist object. It may be possible that you don't know size of arraylist during creation than you can simply use default no argument constructor but if you know size then its best to use overloaded Constructor which takes capacity. Since ArrayList can also be created from another Collection, may be from another List than having another overloaded constructor makes lot of sense. By using overloaded constructor you can converty your ArrayList into Set or any other collection.

    More info with general examples.

提交回复
热议问题