Is it advisable to use two constructors in Java?

-1

hello friends I have a doubt that for me is something I do not understand, builders initialize the objects of a class, but what is the purpose of the overload of builders, in general because there is that term in java ?, because it is possible to create several constructors in java but with different parameters? What is your general purpose?

because example with these two constructors:

  public class HelloWorld{
  
  public HelloWorld(int edad){
    
  }
  public HelloWorld(int  numero){
    
  }
  }
    
asked by simon 16.06.2017 в 02:43
source

2 answers

1

Overloading occurs when you want to execute the same method with different parameters. For example:

public int sumar(int op1, int op2){
    return op1 + op2;
}

public int sumar(int op1, int op2, int op3){
    return op1 + op2 + op3;
}

For the case of the constructors it is the same they serve to have several ways to create an object, an example is the Random class (used to generate random numbers) that has two constructors one that does not ask for parameters and another that asks for a whole number that represents a seed.

    
answered by 16.06.2017 / 03:36
source
1

The overload gives you the possibility of doing the same method with different parameters, in the case of builders, you can do many things with it. A practical example would be to have a constructor that receives an integer and have another that does not receive anything and when this is invoked it calls the other with an integer, it would be like having a default one.

  

public class Example {

     

Example (int x) {

     

System.out.println ("The number is" + x);

     

}

     

Example () {

     

Example (2);

     

}

     

}

This way you can create objects with a default number easily, it is one of the many utilities that have the overload

    
answered by 17.06.2017 в 23:30