Advertisement
LegendSujay2019

Constructor in Java

Aug 26th, 2019
369
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.23 KB | None | 0 0
  1. Constructors in Java
  2. Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection of statements(i.e. instructions) that are executed at time of Object creation.
  3.  
  4. Need of Constructor
  5. Think of a Box. If we talk about a box class then it will have some class variables (say length, breadth, and height). But when it comes to creating its object(i.e Box will now exist in computer’s memory), then can a box be there with no value defined for its dimensions. The answer is no.
  6. So constructors are used to assign values to the class variables at the time of object creation, either explicitly done by the programmer or by Java itself (default constructor).
  7.  
  8. When is a Constructor called ?
  9. Each time an object is created using new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of the same class.
  10.  
  11. A constructor is invoked at the time of object or instance creation. For Example:
  12.  
  13. class Geek
  14. {  
  15.   .......
  16.  
  17.   // A Constructor
  18.   new Geek() {}
  19.  
  20.   .......
  21. }
  22.  
  23. // We can create an object of the above class
  24. // using the below statement. This statement
  25. // calls above constructor.
  26. Geek obj = new Geek();
  27. Rules for writing Constructor:
  28.  
  29. Constructor(s) of a class must has same name as the class name in which it resides.
  30. A constructor in Java can not be abstract, final, static and Synchronized.
  31. Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.
  32. Types of constructor
  33.  
  34. There are two type of constructor in Java:
  35.  
  36. No-argument constructor: A constructor that has no parameter is known as default constructor. If we don’t define a constructor in a class, then compiler creates default constructor(with no arguments) for the class. And if we write a constructor with arguments or no-arguments then the compiler does not create a default constructor.
  37. Default constructor provides the default values to the object like 0, null, etc. depending on the type.
  38.  
  39. filter_none
  40. edit
  41. play_arrow
  42.  
  43. brightness_4
  44. // Java Program to illustrate calling a
  45. // no-argument constructor
  46. import java.io.*;
  47.  
  48. class Geek
  49. {
  50.     int num;
  51.     String name;
  52.  
  53.     // this would be invoked while an object
  54.     // of that class is created.
  55.     Geek()
  56.     {
  57.         System.out.println("Constructor called");
  58.     }
  59. }
  60.  
  61. class GFG
  62. {
  63.     public static void main (String[] args)
  64.     {
  65.         // this would invoke default constructor.
  66.         Geek geek1 = new Geek();
  67.  
  68.         // Default constructor provides the default
  69.         // values to the object like 0, null
  70.         System.out.println(geek1.name);
  71.         System.out.println(geek1.num);
  72.     }
  73. }
  74. Output :
  75.  
  76. Constructor called
  77. null
  78. 0
  79. Parameterized Constructor: A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with your own values, then use a parameterized constructor.
  80. filter_none
  81. edit
  82. play_arrow
  83.  
  84. brightness_4
  85. // Java Program to illustrate calling of
  86. // parameterized constructor.
  87. import java.io.*;
  88.  
  89. class Geek
  90. {
  91.     // data members of the class.
  92.     String name;
  93.     int id;
  94.  
  95.     // constructor would initialize data members
  96.     // with the values of passed arguments while
  97.     // object of that class created.
  98.     Geek(String name, int id)
  99.     {
  100.         this.name = name;
  101.         this.id = id;
  102.     }
  103. }
  104.  
  105. class GFG
  106. {
  107.     public static void main (String[] args)
  108.     {
  109.         // this would invoke the parameterized constructor.
  110.         Geek geek1 = new Geek("adam", 1);
  111.         System.out.println("GeekName :" + geek1.name +
  112.                            " and GeekId :" + geek1.id);
  113.     }
  114. }
  115. Output:
  116.  
  117. GeekName :adam and GeekId :1
  118. Does constructor return any value?
  119.  
  120. There are no “return value” statements in constructor, but constructor returns current class instance. We can write ‘return’ inside a constructor.
  121.  
  122. Constructor Overloading
  123.  
  124. Like methods, we can overload constructors for creating objects in different ways. Compiler differentiates constructors on the basis of numbers of parameters, types of the parameters and order of the parameters.
  125.  
  126. filter_none
  127. edit
  128. play_arrow
  129.  
  130. brightness_4
  131. // Java Program to illustrate constructor overloading
  132. // using same task (addition operation ) for different
  133. // types of arguments.
  134. import java.io.*;
  135.  
  136. class Geek
  137. {
  138.     // constructor with one argument
  139.     Geek(String name)
  140.     {
  141.         System.out.println("Constructor with one " +
  142.                       "argument - String : " + name);
  143.     }
  144.  
  145.     // constructor with two arguments
  146.     Geek(String name, int age)
  147.     {
  148.  
  149.         System.out.println("Constructor with two arguments : " +
  150.                 " String and Integer : " + name + " "+ age);
  151.  
  152.     }
  153.  
  154.     // Constructor with one argument but with different
  155.     // type than previous..
  156.     Geek(long id)
  157.     {
  158.         System.out.println("Constructor with one argument : " +
  159.                                             "Long : " + id);
  160.     }
  161. }
  162.  
  163. class GFG
  164. {
  165.     public static void main(String[] args)
  166.     {
  167.         // Creating the objects of the class named 'Geek'
  168.         // by passing different arguments
  169.  
  170.         // Invoke the constructor with one argument of
  171.         // type 'String'.
  172.         Geek geek2 = new Geek("Shikhar");
  173.  
  174.         // Invoke the constructor with two arguments
  175.         Geek geek3 = new Geek("Dharmesh", 26);
  176.  
  177.         // Invoke the constructor with one argument of
  178.         // type 'Long'.
  179.         Geek geek4 = new Geek(325614567);
  180.     }
  181. }
  182. Output:
  183.  
  184. Constructor with one argument - String : Shikhar
  185. Constructor with two arguments - String and Integer : Dharmesh 26
  186. Constructor with one argument - Long : 325614567
  187. How constructors are different from methods in Java?
  188.  
  189. Constructor(s) must have the same name as the class within which it defined while it is not necessary for the method in java.
  190. Constructor(s) do not return any type while method(s) have the return type or void if does not return any value.
  191. Constructor is called only once at the time of Object creation while method(s) can be called any numbers of time.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement