This process is used when we want to perform multiple tasks in a single constructor rather than creating a code for each task in a single constructor we create a separate constructor for each task and make their chain which makes the program more readable. Every constructor calls up the chain till the class at the top is reached. There could be any number of classes in the inheritance chain. This ensures that the creation of sub class’s object starts with the initialization of the data members of the superclass. A sub-class constructor’s task is to call super class’s constructor first. From base class: by using super() keyword to call the constructor from the base class.Ĭonstructor chaining occurs through inheritance.Within same class: It can be done using this() keyword for constructors in the same class.Prerequisite - Constructors in JavaĬonstructor chaining can be done in two ways: At the time of calling the constructor, memory for the object is allocated in the memory. It is called when an instance of the class is created. Every class has a constructor either implicitly or explicitly. One of the main use of constructor chaining is to avoid duplicate codes while having multiple constructor (by means of constructor overloading) and make code more readable. A constructor is a special method that is called whenever an object is created using the new keyword. A constructors in java is a special method whose name is same as class name and is used to initialize an object. ISRO CS Syllabus for Scientist/Engineer Exam.ISRO CS Original Papers and Official Keys.When a constructor is not explicitly defined for a class, then Java creates a default no-arg. Constructor can have any access modifier public, private, protected or default.
Constructors do not have any return type(not even void). Constructors dont have a return type, even void is not allowed. Constructors in Java : Constructors are similar to methods, but they are used to initialize an object. GATE CS Original Papers and Official Keys Constructor is called automatically when the object is created, in order to initialize an object.