Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about constructors in Java

I have few questions regarding Java constructors

  1. Can a constructor be private? If yes then in which condition?
  2. Is a constructor a method or not?
  3. If a constructor does not return anything then why we are getting a new Object every time we call it?
  4. What's the default access modifier of a constructor if we do not specify.

Edit

The answers for 1 & 3 are very clear. I'm still not sure about 2 & 4 since I'm getting different answers for them.

like image 435
Harry Joy Avatar asked Sep 21 '26 06:09

Harry Joy


1 Answers

Can a constructor be private? If yes then in which condition?

Yes. There are no conditions. Of course, no one except the class itself can call it then.

This is actually a frequent pattern: Have a static getInstance() and keep the constructor private.

There can also be private constructors that the public constructors internally call.

Constructor is a method or not?

Hmm. I say "no". At the very least, it is a "very special kind of" method. In what context exactly? The terminology is less important than what you are trying to do.

If constructor does not return anything then why we are getting a new Object every time we call it.

The new operator returns something (the new instance).

Whats the default access modifier of a constructor.

Same as for methods. Package-private.

If you do not specify any constructor, the class gets a default constructor, which takes no arguments, does nothing except calling the parent constructor and is public.

like image 193
Thilo Avatar answered Sep 24 '26 05:09

Thilo