Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement constructor wrapping in Java?

This is what I'm trying to do (in Java 1.6):

public class Foo {
  public Foo() {
    Bar b = new Bar();
    b.setSomeData();
    b.doSomethingElse();
    this(b);
  }
  public Foo(Bar b) {
    // ...
  }
}

Compiler says:

call to this must be first statement in constructor

Is there any workaround?

like image 957
yegor256 Avatar asked Oct 07 '10 12:10

yegor256


People also ask

How do you implement a constructor in Java?

The two rules for creating a constructor are: The name of the constructor should be the same as the class. A Java constructor must not have a return type. Default Constructor - a constructor that is automatically created by the Java compiler if it is not explicitly defined.

How is constructor implemented?

In Java, a constructor can be overloaded as a feature, of object-oriented programming. Whenever multiple constructors are needed, they are implemented as overloaded methods. It allows more than one constructor inside the class, with a different signature.

How many ways can you make the object for the wrapper class?

The only way to create new Wrapper objects is to use their valueOf() static methods. For example for Integer objects, Integer. valueOf implements a cache for the values between -128 and 127 and returns the same reference every time you call it.


2 Answers

You could implement it like this:

public class Foo {
  public Foo() {
    this(makeBar());
  }
  public Foo(Bar b) {
    // ...
  }
  private static Bar makeBar() {
    Bar b = new Bar();
    b.setSomeData();
    b.doSomethingElse();
    return b;
  }
}

The makeBar method should be static, since the object corresponding to this is not available at the point you are calling the method.

By the way, this approach has the advantage that it does pass a fully initialized Bar object to the Foo(Bar). (@RonU notes that his approach does not. That of course means that his Foo(Bar) constructor cannot assume that its Foo argument is in its final state. This can be problematical.)

Finally, I agree that a static factory method is a good alternative to this approach.

like image 193
Stephen C Avatar answered Oct 05 '22 04:10

Stephen C


You can implement the "default constructor" as a static factory method:

public class Foo {
  public static Foo createFooWithDefaultBar() {
    Bar b = new Bar();
    b.setSomeData();
    b.doSomethingElse();
    return new Foo(b);
  }
  public Foo(Bar b) {
    // ...
  }
}
like image 22
Péter Török Avatar answered Oct 05 '22 03:10

Péter Török