Question about constructors in Java

前端 未结 8 643
我寻月下人不归
我寻月下人不归 2021-01-20 14:52

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?
8条回答
  •  攒了一身酷
    2021-01-20 15:28

    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.

提交回复
热议问题