This article explains constructors in java.
Constructor
Constructor is used for initializing instance variables of a class.
A constructor initializes an object immediately on its creation. The constructor is automatically called when the object is created, before the new operator completes.
Constructor has same name as the class containing it and is syntactically similar to a method. Constructor does not have a return type though since the implicit return type is the class itself.
Here is an example of constructor for Person class :
class Person { String name; int age; Person(){ name = "John"; age = 31; } }
Default and Parameterized constructor
If a constructor does not have any parameters, it is called “default constructor”. If it takes one or more parameters, it is called “parameterized constructor”.
Here is an example of default constructor for Person class :
Person(){ }
Here is an example of parameterized constructor :
Person(String name, int age){ }
Here is the Person class again with a default and parameterized constructor.
class Person { String name; int age; Person(){ name = "John"; age = 31; } Person(String s, int a){ name = s; age = a; } public void display(){ System.out.println("Name = "+ name + ", age = " + age); } } public class Demo { public static void main(String[] args) { Person p1 = new Person(); p1.display(); Person p2 = new Person("Ram",43); p2.display(); } }
While creating object p1, the no-arg constructor is invoked, while for p2, parameterized constructor is called.
The output of this program will be :
Name = John, age = 31
Name = Ram, age = 43
Constructor overloading
Constructor overloading is writing two or more constructors with same name, but different parameters.
In the above example, following constructors were added for the Person class.
Person(){ name = "John"; age = 31; } Person(String s, int a){ name = s; age = a; }
Both the constructors have the same name, but the parameters are different. This is Constructor overloading.
© 2015, https:. All rights reserved. On republishing this post, you must provide link to original post