When an object of a class is made does it always automatically call the constructor?
Daniel Whyte
Level 17
Constructors
Under discussion
Comments (1)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
28 January 2021, 14:49
Yes. When a constructor is not defined in the class code the Java compiler will automatically make a constructor for it that has no input parameters and no code. This is called the default constructor. It will only be there when there are absolutely no other constructors in the class code. If any constructors exist then that feature can't be used and you must call an appropriate constructor when creating an object of the said class. So:
Even with inheritance if the parent class has no constructor then the child class doesn't need one. In that case the default constructor will be made. If there is a constructor with no parameters in the parent class then the child class doesn't need one. In that case the child class will get a default constructor that calls the no parameter parent constructor. If neither of these are true then the child class will need at least one constructor defined that specifically calls one of the parent's constructors:
+2