JPL Expt-4 Minor
JPL Expt-4 Minor
Experiment No. 4
learn how to maintain initialization of multiple constructors from a single location after
having multiple constructors using constructor chaining.
➢ Prerequisites : Students should know how to define java class with importance of class
object and its formation while program execution.
➢ Theory :
- Constructor in java is a special type of method that is used to initialize the object.
- Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
- There are basically two rules defined for the constructor.
Types of Constructors
1] Default Constructor :
◦ The java class without having any constructor implemented within it is called as default
constructor .
◦ If you do not implement any constructor in your class, Java compiler inserts a default
constructor into your code on your behalf.
◦ You would not find it in your source code(the java file) as it would be inserted into the code
during compilation and exists in .class file. This process is shown in the diagram below:
2] No-Argument Constructor :
2] Parameterized constructor
- A constructor that have parameters is known as parameterized constructor.
- Parameterized constructor is used to provide different values to the distinct objects.
- If we want to initialize fields of the class with your own values, then use parameterized constructor.
- We can have any number of parameters in the constructor.
❖ Constructor Chaining :
◦ Calling a constructor from the another constructor of same class is known as Constructor
chaining.
◦ The real purpose of Constructor Chaining is that you can pass parameters through a
bunch of different constructors, but only have the initialization done in a single place.
◦ This allows you to maintain your initializations from a single location, while providing
multiple constructors to the user.
◦ If we don’t chain, and two different constructors require a specific parameter, you will
have to initialize that parameter twice, and when the initialization changes, you’ll have to
change it in every constructor, instead of just the one.
◦ this() and super() are used to call constructors explicitly. Where, using this() you can call
the current class’s constructor and using super() you can call the constructor of the super
class.
◦ From normal (default) constructor you can call the parameterized constructors of the
same class using this() and, from the sub class you can call the constructor of the super
class using super()