Constructors

Constructors
Constructor in Java is block of code which is executed at the time of Object creation. But other than getting called, Constructor is entirely different than methods and has some specific properties like name of constructor must be same as name of Class. Constructor also can not have any return type, constructor’s are automatically chained by using this keyword and super. Since Constructor is used to create object, object initialization code is normally hosted in Constructor. Similar to method you can also overload constructor in Java. In this Java tutorial we will some important points about constructor in Java which is worth remembering for any Java programmer. It’s also worth remember that any static initializer block is executed before constructor because they are executed when class is loaded into memory while constructors are executed when you create instance of any object e.g. using new() keyword.
Constructor in Java – prequestion
Here is some important properties of constructor in Java, these are very specific to constructor only and does not applicable to any other function or method.
1. First and most important rule of declaring constructor is that name of constructor in Java must be exactly same with the class on which you declare constructor, if it doesn't then compiler will flag as error. A class in Java can have as many constructor as it and that is called constructor overloading in Java but signature of two constructor must not be same. here is an example of having multiple constructors in Java and how they are called using new() operator:
public class ConstructorDemo{
public ConstructorDemo(){
System.out.println("Inside no argument constructor");
}
public ConstructorDemo(String name){
System.out.println("Inside one argument constructor in Java with name: " + name);
}
public static void main(String args[]) throws IOException {
ConstructorDemo d = new ConstructorDemo(); //calling no argument constructor in java
ConstructorDemo e = new ConstructorDemo("Testing"); //calling one argument constructor in java
}
}
Output:
Inside no argument constructor
Inside one argument constructor in Java with name: Testing
2. Another important rule of declaring constructor is that constructor in Java doesn't have return type.
3. Every Class in Java has constructor, if no explicit constructor is specified by Programmer, Java Compiler inserts a no argument constructor inside class. This is also called default Constructor in Java. if you provide any constructor in Java e.g. with one argument or two argument than compiler will not add default constructor or no arguments constructor, which makes your class unusable with framework or library which uses reflection and fo
4. One more important property of constructor in Java is constructor chaining. Calling one constructor from another constructor in Java is called Constructor chaining. you can use keyword this for calling constructor of same class and keyword super for calling constructor of super class.
5. You can use any access modifier with Java constructor. they can be public, protected or private. Default or no argument constructor has same access modifier as class. You can also prevent a class from extension by making there constructor private.
6. Constructor in Java can not be abstract, static, final or synchronized. These modifiers are not allowed for constructor.
7. Since parent class is initialized before child class in Java, Constructor of parent class is executed before constructor of child class, that explains why super() is first statement in default no argument constructor.
8.Constructor can throw Exception in Java in fact constructor can declare Exception in there throws clause but that makes caller to handle or re throw Exception while creating any instance of Class.
9.Creating object using new() keyword and constructor has there pros and cons. Its not good in terms of Encapsulation because if you directly create any instance of class you code is tied up with structure of Constructor and any change in constructor will require changes in all places where its object gets created.
10. Unlike C++ there is no destructor in Java. Though objects has finalize method which suppose to run before objects gets garbage collected but that is not guaranteed by Java language specification and it may run or may not.
Types of constructors
There are two types of constructors: -
1. Default constructor (no-arg constructor)
2. Parameterized constructor
1. Default constructor (no-arg constructor)
A constructor that have no parameter is known as default constructor.
Example: -
class Bike{
Bike(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike b=new Bike();
}
}
Output: Bike is created
A default constructor provides the default values to the object like 0, null etc. depending on the type.
Example: -
class Student{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.display();
s2.display();
}
}
Output:0 null
0 null
Parameterized constructor
A parameterized constructor is one that takes multiple arguments/parameters as input. Ex: let us say we want to create multiple constructor for a class Test Public class Test {Public Test() {//code} Public Test(int vals) {//code} Public Test(String val) {//code}}.
Example: -
class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(1976,"Anuj");
Student s2 = new Student(2014,"Babloo");
s1.display();
s2.display();
}
}
Output:1976 Anuj
2014 Babloo
Constructor Overloading: -
Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists.The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.
Example: -
class Student{
int id;
String name;
int age;
Student(int i,String n){
id = i;
name = n;
}
Student(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student s1 = new Student(1976,"Anuj");
Student s2 = new Student(2014,"Babloo",38);
s1.display();
s2.display();
}
}
Output:1976 Anuj 0
2014 Babloo 38
Constructor v/s Method
There are many differences between constructors and methods. They are given below : -
Constructor Method
Constructor is used to initialize the state of an object. Method is used to expose behaviour of an object.
Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default constructor if you don't have any constructor. Method is not provided by compiler in any case.
Constructor name must be same as the class name. Method name may or may not be same as class name.

Copying the values of one object to another in Java: -
There are many ways to copy the values of one object into another. They are: -
* By constructor
* By assigning the values of one object into another
1. By constructor
Example: -
class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}
Student(Student s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(1976,"Anuj");
Student s2 = new Student(s1);
s1.display();
s2.display();
}
}
Output:1976 Anuj
1976 Anuj
2. By assigning the values of one object into another
class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}
Student(){}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(1976,"Anuj");
Student s2 = new Student();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}
Output:1976 Anuj
1976 Anuj


Free Web Hosting