Java Tutorial

What is Java


Control Statements


Java Object Class


Java Inheritance


Java Polymorphism


Java Abstraction


Java Encapsulation


Java Array

Java OOPs Misc


Constructor in Java

Constructor in java is a special type of method that is used to initialize the object.

Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.

Rules for creating java constructor

There are basically two rules defined for the constructor.

  1. Constructor name must be same as its class name
  2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors:

  1. Default constructor (no-arg constructor)
  2. Parameterized constructor

Java Default Constructor

A constructor that have no parameter is known as default constructor.

Syntax of default constructor:

class-name ( ){}
class-name ( ) {body}



Example of default constructor

In this example, we are creating the no-arg constructor in the ConstructorDemo class. It will be invoked at the time of object creation.

package com.ashu;
public class ConstructorDemo {
//creating a default constructor
ConstructorDemo()
{
System.out.println("No argument");
}
public static void main(String[] args) {
//calling a default constructor
ConstructorDemo d = new ConstructorDemo();
}
}


output: No argument


Q) What is the purpose of default constructor?

Default constructor provides the default values to the object like 0, null etc. depending on the type.

Example of default constructor that shows the default values

package com.ashu;
class ConstructorDemo{ int id;
String obj;
boolean b;
//method to display the value of id and name
void show(){
System.out.println(id+" "+obj);
if (true) {
System.out.println(id+" "+b);
}
}
public static void main(String args[]){
//creating objects
ConstructorDemo cd=new ConstructorDemo();
ConstructorDemo cd1=new ConstructorDemo();
//showing values of the object
cd.show();
cd1.show();
}
}


output: false 0 null false 0 null


Explanation:In the above class,you are not creating any constructor so compiler provides you a default constructor.Here 0 and null values are provided by default constructor.

Java parameterized constructor

A constructor that have parameters is known as parameterized constructor.

Why use parameterized constructor?

Parameterized constructor is used to provide different values to the distinct objects.

Parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.

package com.ashu;
public class ConstructorJava64bit{
String studentName;
int studentAge;
//creating a parameterized constructor
ConstructorJava64bit(String name, int age){
studentName = name;
studentAge = age;
}
//method to display the values
void display(){
System.out.println(studentName+ " "+studentAge);
}
public static void main(String args[])
{
//creating objects and passing values
ConstructorJava64bit myObj = new ConstructorJava64bit("Ashutosh" , 24);
myObj.display();
}
}


output: Ashutosh 24


Constructor Overloading in Java

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 of Constructor Overloading

package com.ashu;
class ConstructorJava64bit{
int student_id;
String student_name;
int student_age;
//creating two arg constructor
ConstructorJava64bit(int i,String n){
student_id = i;
student_name = n;
}
void show1(){
System.out.println(student_id+" "+student_name+" "+student_age);
}
//creating three arg constructor
ConstructorJava64bit(int i,String n,int a){
student_id = i;
student_name = n;
student_age=a;
}
void show(){
System.out.println(student_id+" "+student_name+" "+student_age);
}
public static void main(String args[]){
ConstructorJava64bit s1 = new ConstructorJava64bit(011,"sant");
ConstructorJava64bit s2 = new ConstructorJava64bit(022,"ashutosh",26);
s1.show();
s2.show();
}
}


Output: 9 sant 0
18 ashutosh 26

Difference between constructor and method in java

There are many differences between constructors and methods. They are given below.

Java Constructor Java 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.

Java Copy Constructor

There is no copy constructor in java. But, we can copy the values of one object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:

  1. By constructor
  2. By assigning the values of one object into another
  3. By clone() method of Object class

In this example, we are going to copy the values of one object into another using java constructor.

package com.ashu;
class ConstructorJava64bit{
int student_id;
String student_name;
//constructor to initialize integer and string
ConstructorJava64bit(int i,String n){
student_id = i;
student_name = n;
}
//constructor to initialize another object
ConstructorJava64bit(ConstructorJava64bit s){
student_id = s.student_id;
student_name =s.student_name;
}
void show(){
System.out.println(student_id+" "+student_name);
}
public static void main(String args[]){
ConstructorJava64bit s1 = new ConstructorJava64bit(0001,"Santy");
ConstructorJava64bit s2 = new ConstructorJava64bit(s1);
s1.show();
s2.show();
}
}


Output: 1 Santy
1 Santy

Shallow Copying constructor

We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor.

With Copy Constructors we can achieve both Shallow Copy and Deep Copy

package com.ashu;
public class ConstructorJava64bit {
public int x;
public int y;
public Address address;
//Constructor with 2 parameters
public ConstructorJava64bit(int x, int y, Address address) {
super();
this.x = x;
this.y = y;
this.address = address;
}
//Copy Constructor
public ConstructorJava64bit(ConstructorJava64bit p)
{
this.x = p.x;
this.y = p.y;
this.address = p.address; //Shallow Copying
}
public static void main(String[] args)
{
Address address = new Address("Noida","UP");
ConstructorJava64bit p1 = new ConstructorJava64bit(1,2,address);
ConstructorJava64bit p2 = new ConstructorJava64bit(p1);
System.out.println("Before changes");
System.out.println(p1.address.city+" "+p1.address.state);
System.out.println(p2.address.city+" "+p2.address.state);
//Lets change the city and state of P2 object
p2.address.city = "Lucknow";
p2.address.state = "Uttar Pradesh";
System.out.println("After change");
System.out.println(p1.address.city+" "+p1.address.state);
System.out.println(p2.address.city+" "+p2.address.state);
}
}
class Address
{
public String city;
public String state;
public Address(String city, String state)
{
super();
this.city = city;
this.state = state;
}
public Address(Address address)
{
this.city = address.city;
this.state = address.state;
}
}


Output: Before changes
Noida UP
Noida UP
After change
Lucknow Uttar Pradesh
Lucknow Uttar Pradesh

1-The Person class we have two variable x , y and instance of Address class.
2- We have created two objects p1 and p2 (through copy constructor)
3- We have changed the city and state of the cloned object p2, but it gets reflected in the original object p1 object also.
4 -This is because shallow copying, the Address member of the both original object p1,
5- cloned object p2 refers to the same memory location.

Deep Copying:

Lets now change our implementation from shallow Copying to deep Copying.

package com.ashu;
public class ConstructorJava64bit
{
public int x;
public int y;
public Address address;
//Constructor with 2 parameters
public ConstructorJava64bit(int x, int y, Address address)
{
super();
this.x = x;
this.y = y;
this.address = address;
}
//Copy Constructor
public ConstructorJava64bit(ConstructorJava64bit p) {
this.x = p.x;
this.y = p.y;
this.address = new Address(p.address); //Deep Copying
}
public static void main(String[] args)
{ Address address = new Address("Noida","UP");
ConstructorJava64bit p1 = new ConstructorJava64bit(1,2,address);
ConstructorJava64bit p2 = new ConstructorJava64bit(p1);
System.out.println(" Before changes ");
System.out.println(p1.address.city+" "+p1.address.state);
System.out.println(p2.address.city+" "+p2.address.state);
//Lets change the city and state of P2 object
p2.address.city = "Lucknow";
p2.address.state = "Uttar Pradesh";
System.out.println(" After change ");
System.out.println(p1.address.city+" "+p1.address.state);
System.out.println(p2.address.city+" "+p2.address.state);
}
}
class Address
{
public String city;
public String state;
public Address(String city, String state)
{
super();
this.city = city;
this.state = state;
}
public Address(Address address)
{
this.city = address.city;
this.state = address.state;
}
}

Output: Before changes
Noida UP
Noida UP
After change
Noida UP
Lucknow Uttar Pradesh

Q) Does constructor return any value?

Ans:yes, that is current class instance (You cannot use return type yet it returns a value).

Can constructor perform other tasks instead of initialization?

Yes, like object creation, starting a thread, calling method etc. You can perform any operation in the constructor as you perform in the method.

Copyright 2017 Design& Development