Advantages of Constructor Overloading

前端 未结 6 1855
青春惊慌失措
青春惊慌失措 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条回答
  •  旧时难觅i
    2021-01-18 11:46

    Considering the simplest example of constructor overloading :

    Class A
    {
    int a;
    
    A()
    {
    this.a = 0;
    }
    
    A(int a)
    {
    this.a = a;
    }
    
    } // end class
    

    Advantage: Now I may simply need to use the default constructor new A() to assign default values or for a more dynamic case specify what value it must be new A(10) which is a parametrised constructor. do read this question

    Isn't it easier to Overload Methods using single constructor for flexibility?

    Job of constructor is to instantiate the object , and the job of the method is to process the object values. Thus limiting methods to processing (exception to setter methods) and constructor to creation of object will help in a long run and also make your class more usable to your team-mates

    Moreover if I am trying to use constructor overloading to use one object to initialize another, there are simpler ways to do it!

    alternative is initializer , also read

提交回复
热议问题