Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloaded constructor calling other constructor, but not as first statement

Tags:

I'm having some trouble using multiple constructors in java.

what I want to do is something like this:

public class MyClass {

 // first constructor
 public MyClass(arg1, arg2, arg3) {
  // do some construction
 }

 // second constructor
 public MyClass(arg1) {
      // do some stuff to calculate arg2 and arg3
      this(arg1, arg2, arg3);
    }
}

but I can't, since the second constructor cannot call another constructor, unless it is the first line.

What is the common solution for such situation? I can't calculate arg2 and arg3 "in line". I thought maybe creating a construction helper method, that will do the actual construction, but I'm not sure that's so "pretty"...

EDIT: Using a helper method is also problematic since some of my fields are final, and I can't set them using a helper method.

like image 396
David B Avatar asked Aug 02 '10 08:08

David B


2 Answers

Typically use another common method - a "construction helper" as you've suggested.

public class MyClass { 

    // first constructor 
    public MyClass(arg1, arg2, arg3) { 
      init(arg1, arg2, arg3); 
    } 

    // second constructor 
    public MyClass(int arg1) { 
      // do some stuff to calculate arg2 and arg3 
      init(arg1, arg2, arg3); 
    } 

    private init(int arg1, int arg2, int arg3) {
      // do some construction 
    }
} 

The alternative is a Factory-style approach in which you have a MyClassFactory that gives you MyClass instances, and MyClass has only the one constructor:

public class MyClass { 

    // constructor 
    public MyClass(arg1, arg2, arg3) { 
      // do some construction 
    } 
} 

public class MyClassFactory { 

    public static MyClass MakeMyClass(arg1, arg2, arg3) { 
      return new MyClass(arg1, arg2, arg3);
    } 

    public static MyClass MakeMyClass(arg1) { 
      // do some stuff to calculate arg2 and arg3 
      return new MyClass(arg1, arg2, arg3);
    } 
} 

I definitely prefer the first option.

like image 130
Matt Mitchell Avatar answered Sep 27 '22 21:09

Matt Mitchell


Next possible solution is Factory method. These static methods can be overloaded and after calculation they can call the private / protected constructor

public class MyClass {

    private MyClass( arg1, arg2, arg3 ) {
         // do sth
    }

    public static MyClass getInstance( arg1 ) {
         // calculate arg2,3
        return new MyClass( arg1, arg2, arg3 );
    }

    public static MyClass getInstance( arg1, arg2, arg3 ) {
        return new MyClass( arg1, arg2, arg3 );
    }
}

EDIT: This method is also ideal when you have a final fields

like image 30
Gaim Avatar answered Sep 27 '22 20:09

Gaim