Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with 2 almost identical constructors [duplicate]

If I have 2 constructors in my custom class and one of them takes an extra argument and does everything the first one does but with just one additional line of code (and this extra line utilises the extra argument), how best to deal with this without having to duplicate all the code in the first constructor?

Example code

public myConstuctor(int number, int number2){

    int result = (number + number2);
    int result2 = (number2 - number1)

    //Etc
    //Etc
    //Etc
    //Etc

}

public myConstructor(int number1, int number2, int number 3){

    int result = (number + number2);
    int result2 = (number2 - number1)

    //Etc
    //Etc
    //Etc
    //Etc

    int result3 = (result + result2 + number3)


}
like image 342
Zippy Avatar asked Aug 12 '13 16:08

Zippy


People also ask

Can we have two constructors with same parameters?

There can be multiple constructors in a class. However, the parameter list of the constructors should not be same. This is known as constructor overloading.

Can you have 2 constructors with the same name in Java?

The technique of having two (or more) constructors in a class is known as constructor overloading. A class can have multiple constructors that differ in the number and/or type of their parameters. It's not, however, possible to have two constructors with the exact same parameters.

How do you avoid code duplication in C++?

The C++11 delegating constructors reduce the code duplication and make effective use of the member initializer lists.


2 Answers

You can make the second constructor call the first one:

public MyClass(int number1, int number2, int number3) {
    this(number1, number2);
like image 177
SLaks Avatar answered Oct 23 '22 16:10

SLaks


You can call the other constructor and put all of your logic there.

public myConstructor(int number, int number2){
    this(number, number2, 0);
}

public myConstructor(int number1, int number2, int number3){

    int result = (number + number2);
    int result2 = (number2 - number1)

    //Etc
    //Etc
    //Etc
    //Etc

    int result3 = (result + result2 + number3)


}
like image 34
bas Avatar answered Oct 23 '22 17:10

bas