-7

What are the advantages/disadvantages of init method over a constructor in java? They both have the same purpose. How to choose between them?

public class A {    
  private int x;

  public A(int x){
    this.x = x;
  }

  public void init(int x){
   this.x = x;
  }
}

Here we can use either constructor or init method.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • 4
    "they both have the same purpose", no they don't. you'll always need a constructor. an init method can come in handy if all your constructors contain identical code, but then I would recommend making it private, so that a subclass won't change it. – Stultuske Nov 13 '17 at 13:43

2 Answers2

3

You are wrong. They do not have the same purpose.

A constructor is always required when you want to create a new object using the new() operator.

A init method is something that might make sense in certain contexts, for example servlet stuff (see here for further reading regarding this aspect).

And please note: in your example, one could your init method more as a setter - as it is simply setting the corresponding field.

Coming from there:

  • first of all, you think about the constructors that you want to put into you class (by asking: which information is required to create a new instance of the class)
  • if there is special need, then consider adding setters for specific fields - or as layed out above, it might be required to provide an init() method (in case where object creation and initializiation can not happen at the same point of time)
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Thanks for the reply. I agree with what you are saying. My question is both init method and parameterized constructor is used for initializing an object. – codebuffer Nov 13 '17 at 13:57
  • Which one you prefer ? and why? – codebuffer Nov 13 '17 at 13:57
  • I think I answered both questions. You start with one or more constructors. You use init methods if you have to. That is all there is to this. – GhostCat Nov 13 '17 at 14:12
1

Constructor is not a regular method. It's special in a sense that it gets always called when you invoke new A(). If you don't provide a constructor, Java creates one automatically. As a consequence, constructors do not have a return (i.e. they return this) and always have the same name as the class.

On the other hand, init is a regular method, which you can call - or not. There is no universally accepted consensus for any kind of "init" methods. So it depends on what you want to do. If you want to ensure that the new calls your logic, use constructor. If you want to have your own stuff, use plain methods. You can mix and match, just be sure to write a good documentation about how your class is supposed to be used.

jurez
  • 4,436
  • 2
  • 12
  • 20