Can we override a constructor in Java and can a constructor be private?

后端 未结 11 1807
旧时难觅i
旧时难觅i 2020-12-29 14:21

I would appreciate an explanation for these questions:

  1. Can we Override a constructor in Java?
  2. Can a Constructor be private?<
相关标签:
11条回答
  • 2020-12-29 15:07

    1) NO! A constructor belongs to the class in which it is declared. A sub class is a different class and must have its own constructor. So, constructors simply can't be overridden.

    2) Yes, that's done usually in case of singletons.

    0 讨论(0)
  • 2020-12-29 15:09
    1. In a derived class you can create a new constructor with the same signature but that is not really overriding since, when initializing the class, the parent class's constructor is still called before the new one.

    2. a class's constructor can be private or protected and of course be public. but if it is protected or private how would you initiate the class? ( actually you could with a static function in that class...)

    0 讨论(0)
  • 2020-12-29 15:13

    1) Is this just homework question, or do you try to reach something? Can you show what you try to reach with an overriding constructor?

    Since the parent constructor is called first, you may modify the base class to your needs in your constructor. Of course, just as far as the access to base attributes isn't private. If you extend a class but don't like their might-be-private attributes, deriving from it was an error.

    2) Can a constructor be private?

    Yes, but do you know what it is good for?

    0 讨论(0)
  • 2020-12-29 15:16

    Both are not true ,as when a class inherit other class it automatically calls its parents class ,so it makes sense that we can't override and make them final .

    0 讨论(0)
  • 2020-12-29 15:19

    Constructor is meant for a class. It cant be overridden under any circumstances. Its like wanting to change Ferrari's factory from BMW's factory (which isn't practical). Surely you can overload to get the functionality you need.

    Yes Constructor can be private. By making it private you are not letting the outside world to create an object of it directly through constructor, But singleton pattern uses a public static method to call the constructor of the class and object can be created.

    0 讨论(0)
提交回复
热议问题