Constructor
Constructor
Q5) What happens when the class does not contain any constructor?
Ans :- If a class does not contain any constructor, then compiler creates a default constructor which
initializes data members for the object using default values provided by java for different data types.
Uses / significance:-
i) it is useful in returning the object address of which the function is a member.
ii) to refer to the data member, in case it matches with the local variable.
iii) used in constructor to initialize the data members.
Example: -
i) Class Rectangle
double diagonal;
Rectangle()//default constructor
{ this(10,8,10.0); }
{ this.length=length;
this.breadth=breadth;
this.diagonal=diagonal;
this ( 1, 0.0);
void input( int roll, double average)// referring to the data member, if it matches with the local variable
{ this.roll= roll;
}}
Q 10) What is Constructor Overloading? What is its need?
Ans :- When more than one constructor is used in a class, it is called Constructor Overloading. Each
Constructor should have different signature (Parameter List).
Sometimes it is required to create an object using default Constructor and sometime using
parameterized constructor.
Q 11) What are the differences between a method (function) and a Constructor?
Parameters Method ( Function) Constructor
Name Functions have name other than class name. Constructor has name same as that of the
class.
Need To avoid repetition and to increase code To initializes the member variables.
reusability.
Return type They have a return type specifier. They do not have a return type specifier.
Specifier
Return value It may or may not return any value. It does not return any value, not even
void.
Order of It can be executed repeatedly as and when It gets invoked automatically at the time
execution required by giving a call to method name. of creating an object of the class.
**************************