Constructors are the important part of the Java code, so I tried to list out the 10 points which we must know about constructors while writing the code, for interview or for an exam.
1. First of all as we all know constructor name must always match the name of the class.
2. The default constructor for the class is always a no argument constructor. This constructor is automatically generated if do not write any constructor in our code. This constructor is generated by a compiler.
3. Third most important thing to know that constructor in any case doesn't have a return type.
4. Constructor can have any access modifier such as public, protected private etc. So as per rule of private if we have private access modifier for constructor then we need to instantiate the object within the class code itself.
5. First statement of the constructor is either this() for calling overloaded constructor or super() which calls the superclass constructor.
6. So what if we do not write this() or super() as a first statement in constructor??? No worries, compiler will insert super() as a first statement of constructor.
7. super() call inserted by compiler ( as we saw in above point ) is always non argument constructor but we can write super() with arguments as a first statement of constructor. Suppose super class doesn't have no argument constructor then in that case we need to call super() with arguments matching with the super class constructor.
8. If we have this() call as a first line of constructor then argument list determines which overloaded constructor needs to be called. Remember we cant have super() and this() both in same constructor.
9. As interfaces don't come as a part of inheritance tree , they doesn't have constructors , but abstract classes do have.
10. We do not invoke constructors as we invoke methods, constructors can be invoked from another constructors only.
If I have missed some points , you can add it in comments, if you liked this article don't wait share it. :)
- Blogger Comment
- Facebook Comment