{"id":817,"date":"2016-02-25T07:51:27","date_gmt":"2016-02-25T07:51:27","guid":{"rendered":"http:\/\/abhiandroid.com\/java\/?page_id=817"},"modified":"2016-02-25T07:51:27","modified_gmt":"2016-02-25T07:51:27","slug":"constructor","status":"publish","type":"page","link":"https:\/\/abhiandroid.com\/java\/constructor","title":{"rendered":"Constructor In Java With Example"},"content":{"rendered":"<p>A constructor is a special method that is called whenever an object is created using the <strong>new <\/strong>keyword. It contains a block of statements that is used to initialize instance variables of an object before the reference of this object is returned by <strong>new<\/strong>.\u00a0Constructor\u00a0can be defined as a method having same name as class name without any return type.<\/p>\n<p><span style=\"color: #ff0000;\"><strong>Important Note:<\/strong><\/span> A constructor does look and feel a lot like a method but it is different from a method in two ways:<\/p>\n<ul>\n<li>A constructor always has a same name as the class whose instance members they initialize.<\/li>\n<li>A constructor does not have a return type, not even void. It is because the constructor is automatically called by the compiler whenever an object of the class is created.<\/li>\n<\/ul>\n<hr \/>\n<h4><span style=\"color: #008000;\"><span style=\"color: #000000;\"><strong>Need of Constructor:<\/strong><\/span><\/span><\/h4>\n<p>Initializing a variable is very helpful while making programs. We can initialize variables of primitive types at the time of their declarations. For example:<\/p>\n<p>int a=10;<\/p>\n<p>In object oriented programming language (OOPL) like java, the need of initialization of fields of a new object is even more common. It can be done by using following two approaches:<\/p>\n<ul>\n<li>In the first approach we use a dot operator to access and assign values to the instance variables for each object individually. However it can be tedious job to initialize the instance variables of all objects individually. Moreover, it does not promote data hiding.<\/li>\n<li>In second approach we make use of method to assign values to fields of each object individually. But it would have to be called explicitly for each object. This would be inconvenient if the number of objects is very large.<\/li>\n<\/ul>\n<p>A better solution to the above problems is to initialize values to the object at a time of its creation in the same way as we initialize values to the variable of primitive data types. This is accomplished using a special method in java known as <strong>constructor<\/strong> that makes an object to initialize itself at the time of its creation without the need to make separate call to the instance method.<\/p>\n<hr \/>\n<h4><span style=\"color: #000000;\"><strong>Syntax of Constructor:<\/strong><\/span><\/h4>\n<p>The syntax of constructor is as follows:<\/p>\n<pre class=\"\">ConstructorName([parameterList])\r\n\r\n{\r\n\r\n  \/\/constructor body\r\n\r\n}<\/pre>\n<p>Here, the <strong>constructorName<\/strong> is same as the name of class it belongs to.<\/p>\n<p>The <strong>parameterList<\/strong> is the list of optional zero or more parameters that are specified after the class name in the parenthesis. Each parameter specification, if any, consists of a type and a name and are separated from each other by commas.<\/p>\n<p>Let us consider the <strong>program <\/strong>that gives us the use of constructor to initialize the instance variables of the newly created object.<\/p>\n<p>Firstly we make a class <strong>Rectangle<\/strong> in which we declare constructor and method to show how to use it:<\/p>\n<pre class=\"\">\/\/use of constructor\r\n\r\nclass Rectangle\r\n\r\n{\r\n\r\n  int length;\r\n\r\n  int breadth;\r\n\r\n  \/\/declare constructor to initialize length and breadth of rectangle\r\n\r\n  Rectangle()\r\n\r\n  {\r\n\r\n    length=5;\r\n\r\n    breadth=6;\r\n\r\n  }\r\n\r\n  \/\/declare method to calculate area of rectangle\r\n\r\n  int area()\r\n\r\n  {\r\n\r\n    int rectArea=length*breadth;\r\n\r\n    return rectArea;\r\n\r\n  }\r\n\r\n}<\/pre>\n<p>Then we create a class <strong>ConstructorDemo<\/strong> which inherits the above class <strong>Rectangle<\/strong> and is used to create objects of the Rectangle class and calculate its area:<\/p>\n<pre class=\"\">\/\/class to create a rectangle objects and calculate area\r\n\r\nclass ConstructorDemo\r\n\r\n{\r\n\r\n  public static void main(String args[])\r\n\r\n  {\r\n\r\n    Rectangle r=new Rectangle();\r\n\r\n    System.out.println(\"Area of rectangle=\"+r.area());\r\n\r\n  }\r\n\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"\">Area of rectangle= 30<\/pre>\n<p><strong>Explanation:<\/strong><\/p>\n<ul>\n<li>In the above program when the statement:\u00a0<strong>Rectangle r=new Rectangle();\u00a0<\/strong>is executed the new operator creates a new but object of the class that is uninitialized.<\/li>\n<li>Then the constructor(Rectangle()) is called and the statements in its body are executed.<\/li>\n<li>Then the address of the allocated <strong>Rectangle <\/strong>object is returned and assigned to the reference variable <strong>r<\/strong>. This method of initializing instance variables of an objects using constructor is very simple and concise as there is no need to explicitly or directly call the method of each object separately.<\/li>\n<\/ul>\n<hr \/>\n<h4><span style=\"color: #000000;\">\u00a0<strong>Types of Constructor:<\/strong><\/span><\/h4>\n<p>There are three types of constructors. These are:<\/p>\n<ul>\n<li><strong>Default Constructor &#8211;<\/strong> Compiler automatically creates one constructor if we don&#8217;t create<\/li>\n<li><strong>Parameterized Constructor &#8211;<\/strong> Constructor with\u00a0parameter which make possible\u00a0to initialize objects with different set of values at time of their creation<\/li>\n<li><strong>Copy Constructor &#8211;<\/strong> Constructor which\u00a0creates a new object using an existing object of the same class and initializes each instance variable of newly created object with corresponding instance variables of the existing object passed as argument<\/li>\n<\/ul>\n<p>Below we have\u00a0describe all three constructor in detail with example:<\/p>\n<hr \/>\n<h4><strong>Default Constructor:<\/strong><\/h4>\n<p>Each time an object is created, a constructor is always invoked. But in some programs if we don\u2019t create any constructor. So in such situations, the compiler automatically creates one constructor which is known as default constructor. It does not contain any parameters and doesn\u2019t even contain any statements in its body. Its only purpose is to enable you to create object of class type. The default constructor looks like:<\/p>\n<pre class=\"\">public Rectangle(){}<\/pre>\n<p><span style=\"color: #ff0000;\"><strong>Important Note: <\/strong><\/span>Constructors are invoked only after the instance variables of a newly created object of the class have been assigned their default initial values and after their explicit initializers are executed.<\/p>\n<p><span style=\"color: #008000;\"><strong>Program Example of Default Constructor:<\/strong><\/span><\/p>\n<p>Let us consider a program to demonstrate the use of the default values, initialize expressions and constructors.<\/p>\n<p>Firstly we create a class <strong>Display<\/strong> in which we declare default constructor:<\/p>\n<pre class=\"\">class Display\r\n\r\n{\r\n\r\n  int a=6; \/\/initializer expression\r\n\r\n  int b=5; \/\/initializer expression\r\n\r\n  int c; \/\/assigned default value\r\n\r\n  Display()\r\n\r\n  {\r\n\r\n    a=4; \/\/override default and initializer expression\r\n\r\n  }\r\n\r\n  void show()\r\n\r\n  {\r\n\r\n    System.out.println(\"Value of a=\"+a);\r\n\r\n    System.out.println(\"Value of b=\"+b);\r\n\r\n    System.out.println(\"Value of c=\"+c);\r\n\r\n  }\r\n\r\n}<\/pre>\n<p>Then we create a class <strong>DisplayDemo<\/strong> which inherits the methods from above class <strong>Display<\/strong>:<\/p>\n<pre class=\"\">class DisplayDemo\r\n\r\n{\r\n\r\n  public static void main(String args[])\r\n\r\n  {\r\n\r\n    Display data=new Display();\r\n\r\n    data.show();\r\n\r\n  }\r\n\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"\">Value of a= 4\r\nValue of b= 5\r\nValue of c= 0<\/pre>\n<hr \/>\n<h4><strong>Parameterized Constructor:<\/strong><\/h4>\n<p>The constructor which has parameters is known as parameterized constructor. Using parameterized constructor, it is possible to initialize objects with different set of values at time of their creation. These different set of values initialized to objects must be passed as arguments when constructor is invoked. The parameter list can be specified in the parenthesis in the same way as parameter list is specified in the method.<\/p>\n<p><span style=\"color: #008000;\"><strong>Program Example of Parameterized Constructor:<\/strong><\/span><\/p>\n<p>Let us consider a program to understand the concept of parameterized constructor.<\/p>\n<p>First we make a class <strong>Rectangle<\/strong> in which we declare the parametrized constructor:<\/p>\n<pre class=\"\">class Rectangle\r\n\r\n{\r\n\r\n  int length;\r\n\r\n  int breadth;\r\n\r\n  \/\/constructor to initialize length and breadth of rectangle\r\n\r\n  Rectangle(int l, int b)\r\n\r\n  {\r\n\r\n    length=l;\r\n\r\n    breadth=b;\r\n\r\n  }\r\n\r\n  \/\/method to calculate area of rectangle\r\n\r\n  int area()\r\n\r\n  {\r\n\r\n    return (length*breadth);\r\n\r\n  }\r\n\r\n}\r\n<\/pre>\n<p>Second we create a class <strong>ParamConstructorDemo<\/strong> which inherit the methods of above class <strong>Rectangle<\/strong> and create the object of <strong>Rectangle<\/strong> class and calculate its area:<\/p>\n<pre class=\"\">\/\/class to create a rectangle objects and calculate area\r\n\r\nclass ParamConstructorDemo\r\n\r\n{\r\n\r\n  public static void main(String args[])\r\n\r\n  {\r\n\r\n    Rectangle firstRect=new Rectangle(5,6);\r\n\r\n    Rectangle secondRect=new Rectangle(7,8);\r\n\r\n    System.out.println(\"Area of first rectangle=\"+firstRect.area());\r\n\r\n    System.out.println(\"Area of second rectangle=\"+secondRect.area());\r\n\r\n  }\r\n\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"\">Area of first rectangle= 30\r\nArea of second rectangle= 56<\/pre>\n<hr \/>\n<h4><strong>Copy Constructor:<\/strong><\/h4>\n<p>Sometimes a programmer wants to create an exact but separate copy of an existing object so that any changes to the copy should not alter the original or vice versa. This is made possible by using the copy constructor. A copy constructor is a constructor that creates a new object that is using an existing object of the same class and initializes each instance variable of newly created object with corresponding instance variables of the existing object passed as argument. This constructor takes a single argument whose type is that of the class containing the constructor.<\/p>\n<p><span style=\"color: #008000;\"><strong>Program Example of Copy Constructor:<\/strong><\/span><\/p>\n<p>Let us consider a program in which we create a copy of an existing object.<\/p>\n<p>First we create a class <strong>Rectangle<\/strong> in which we declare the copy constructor to initialize length and breadth:<\/p>\n<pre class=\"\">class Rectangle\r\n\r\n{\r\n\r\n  int length;\r\n\r\n  int breadth;\r\n\r\n  \/\/constructor to initialize length and breadth of rectangle\r\n\r\n  Rectangle(int l, int b)\r\n\r\n  {\r\n\r\n    length=l;\r\n\r\n    breadth=b;\r\n\r\n  }\r\n\r\n  \/\/copy constructor\r\n\r\n  Rectangle(Rectangle obj)\r\n\r\n  {\r\n\r\n    System.out.println(\"copy constructor invoked\");\r\n\r\n    length=obj.length;\r\n\r\n    breadth=obj.breadth;\r\n\r\n  }\r\n\r\n  \/\/method to calculate area of rectangle\r\n\r\n  int area()\r\n\r\n  {\r\n\r\n    return (length*breadth);\r\n\r\n  }\r\n\r\n}<\/pre>\n<p>Second we create a class <strong>CopyConstructorDemo<\/strong> which inherit the methods of above class <strong>Rectangle<\/strong> and create its object and calculate area:<\/p>\n<pre class=\"\">\/\/class to create a rectangle objects and calculate area\r\nclass CopyConstructorDemo\r\n\r\n{\r\n\r\npublic static void main(String args[])\r\n\r\n{\r\n\r\nRectangle firstRect=new Rectangle(5,6);\r\n\r\nRectangle secondRect=new Rectangle(firstRect);\r\n\r\nSystem.out.println(\"Area of first rectangle=\"+firstRect.area());\r\n\r\nSystem.out.println(\"Area of second rectangle=\"+secondRect.area());\r\n\r\n}\r\n\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"\">Copy constructor invoked\r\nArea of first rectangle= 30;\r\nArea of second rectangle= 30;<\/pre>\n<hr \/>\n<h4>\u00a0<span style=\"color: #000000;\"><strong>Constructor Overloading:<\/strong><\/span><\/h4>\n<p>Constructor can be overloaded in the same way as you can overload methods. <strong>Constructor overloading <\/strong>allows a class to have more than one constructor that have same name as that of the class but differs only in terms of number of parameters or parameter\u2019s data type or both. By overloading a constructor for a class, we make the class more versatile as it allows you to construct objects in a variety of ways.<\/p>\n<p><span style=\"color: #008000;\"><strong>Program Example of Constructor Overloading:<\/strong><\/span><\/p>\n<p>In order to understand the concept of constructor overloading, let us consider the following program.<\/p>\n<p>First we create class <strong>Rectangle<\/strong> in which we declare more than one constructor of same name to show constructor overloading:<\/p>\n<pre class=\"\">\/\/constructor overload\r\n\r\nclass Rectangle\r\n\r\n{\r\n\r\n  int length;\r\n\r\n  int breadth;\r\n\r\n  Rectangle()\r\n\r\n  {\r\n\r\n    System.out.println(\"Constructor with zero parameter called\");\r\n\r\n    length=breadth=0;\r\n\r\n  }\r\n\r\n  Rectangle(int side)\r\n\r\n  {\r\n\r\n    System.out.println(\"constructor with one parameter called\");\r\n\r\n    length=breadth=side;\r\n\r\n  }\r\n\r\n  Rectangle(int l,int b)\r\n\r\n  {\r\n\r\n    System.out.println(\"constructor with two parameters called\");\r\n\r\n    length=l;\r\n\r\n    breadth=b;\r\n\r\n  }\r\n\r\n  int area()\r\n\r\n  {\r\n\r\n    return(length*breadth);\r\n\r\n  }\r\n\r\n}<\/pre>\n<p>Second we create class <strong>ConstructorOverload<\/strong> which inherits the above class <strong>Rectangle<\/strong>:<\/p>\n<pre class=\"\">class ConstructorOverload\r\n\r\n{\r\n\r\n  public static void main(String args[])\r\n\r\n  {\r\n\r\n    Rectangle r1=new Rectangle();\r\n\r\n    Rectangle r2=new Rectangle(5);\r\n\r\n    Rectangle r3=new Rectangle(7,8);\r\n\r\n    System.out.println(\"Area of first rectangle=\"+r1.area());\r\n\r\n    System.out.println(\"Area of square=\"+r2.area());\r\n\r\n    System.out.println(\"Area of second rectangle=\"+r3.area());\r\n\r\n  }\r\n\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"\">Constructor with zero parameter called\r\nConstructor with one parameter called\r\nConstructor with two parameters called\r\nArea of first rectangle= 0\r\nArea of square= 25\r\nArea of second rectangle= 56\r\n<\/pre>\n<p><strong>Explanation of Example: <\/strong><\/p>\n<p>In the above program, the class Rectangle contains three constructor with the same name Rectangle which differ only in the number of parameters and hence overloaded.<\/p>\n<hr \/>\n<h4>\u00a0<span style=\"color: #000000;\"><strong>Important Points to Remember About Constructor:<\/strong><\/span><\/h4>\n<ul>\n<li>No class can exist without any constructor.<\/li>\n<li>If there is no constructor in a class then one non parameterized (default) constructor is inserted in that class by the compiler.<\/li>\n<li>Copy constructor is used to create a duplicate copy of existing object.<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>A constructor is a special method that is called whenever an object is created using the new keyword. It contains a block of statements that is used to initialize instance variables of an object before the reference of this object is returned by new.\u00a0Constructor\u00a0can be defined as a method having same name as class name &hellip; <a href=\"https:\/\/abhiandroid.com\/java\/constructor\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Constructor In Java With Example<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"open","ping_status":"closed","template":"home.php","meta":{"footnotes":""},"class_list":["post-817","page","type-page","status-publish","hentry"],"psp_head":"<title>Constructor In Java With Example \u2013 Abhi Android<\/title>\r\n<meta name=\"description\" content=\"Tutorial on constructor and its types (default constructor, parametric and copy constructor) with example in JAVA. A constructor is a special method that is called whenever an object is created using the new keyword.\" \/>\r\n<meta name=\"robots\" content=\"index,follow\" \/>\r\n<link rel=\"canonical\" href=\"https:\/\/abhiandroid.com\/java\/constructor\" \/>\r\n","_links":{"self":[{"href":"https:\/\/abhiandroid.com\/java\/wp-json\/wp\/v2\/pages\/817","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/abhiandroid.com\/java\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/abhiandroid.com\/java\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/java\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/java\/wp-json\/wp\/v2\/comments?post=817"}],"version-history":[{"count":0,"href":"https:\/\/abhiandroid.com\/java\/wp-json\/wp\/v2\/pages\/817\/revisions"}],"wp:attachment":[{"href":"https:\/\/abhiandroid.com\/java\/wp-json\/wp\/v2\/media?parent=817"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}