Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I call methods in constructor in Java?

I have situation, where I want to read configuration file only one time, when class is instantiated.

Suppose I have a method named readConfig(), that reads configuration and puts it into a Map object. When the program is required to use configuration value it reads object with it's define key. I want to know that constructor calls only once it's life cycle. Can I put my method readConfig() into constructor, which would give me benefit of one time calling or is there another mechanism to do that?

like image 946
Sameek Mishra Avatar asked Mar 08 '11 09:03

Sameek Mishra


People also ask

Is it bad to call methods in constructor?

You shouldn't: calling instance method in constructor is dangerous because the object is not yet fully initialized (this applies mainly to methods than can be overridden). Also complex processing in constructor is known to have a negative impact on testability.

Can you put methods in constructors?

A constructor can call methods, yes. A method can only call a constructor in the same way anything else can: by creating a new instance. Be aware that if a method constructs a new object of the same type, then calling that method from a constructor may result in an infinite loop...

Can we call other methods from constructor?

No, you cannot call a constructor from a method. The only place from which you can invoke constructors using “this()” or, “super()” is the first line of another constructor. If you try to invoke constructors explicitly elsewhere, a compile time error will be generated.


2 Answers

You can: this is what constructors are for. Also you make it clear that the object is never constructed in an unknown state (without configuration loaded).

You shouldn't: calling instance method in constructor is dangerous because the object is not yet fully initialized (this applies mainly to methods than can be overridden). Also complex processing in constructor is known to have a negative impact on testability.

like image 162
Tomasz Nurkiewicz Avatar answered Sep 24 '22 17:09

Tomasz Nurkiewicz


Better design would be

public static YourObject getMyObject(File configFile){     //process and create an object configure it and return it } 
  • Factory design pattern
like image 42
jmj Avatar answered Sep 21 '22 17:09

jmj