Question about constructors in Java

前端 未结 8 646
我寻月下人不归
我寻月下人不归 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:32

    The default access modifier of a constructor is CLASS ACCESS MODIFIER, If a class is public , then access modifier of a constructor is public. If the class is default , then constructor is also default.

    0 讨论(0)
  • 2021-01-20 15:33
    1. Yes, in any case. However, if all constructors for a class are private, that means that the class cannot be directly instantiated. You will need to use something like the Factory Pattern to create instances of the object.
    2. Yes, the constructor is a method.
    3. A better way to think about it is that the new operator returns the object and in the process of creating the object, calls the constructor. Another way to think about it (although this is only a way to think about it, it isn't technically correct) is simply that the return type is implied by convention. A good place to read more about this is to read about new in the context of C++. The constructor's role is not to create the object but rather to initialize the memory contained within the object.
    4. Default access for a constructor in Java is package private just like any other method. (One such source: http://www.javabeginner.com/learn-java/introduction-to-java-access-modifiers and from the horse's mouth: http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)
    0 讨论(0)
提交回复
热议问题