Constructor
Constructor
Constructor are special methods which are used to initialize the object.
A constructor has same name as that of class.
It does not have any return type.
e.g. class Rock
{
Rock()
//default constructor
{}
}
If you do not provide the constructor then compiler create a default constructor.
A default constructor is a non-argument constructor.
If you create a constructor then compiler will not create default constructor for
you.
Important points for constructor:
Constructor are not inherited.
They are called in the order of inheritance.
They can be overloaded but can not be overridden.
You can not create a single object without a constructor.
‘Super’ is use to call the desired version of superclass constructor.
Call to the ‘super’ must be the first statement in constructor.
‘This’ keyword can be used for inter constructor communication.
Types of constructors:
1) Default constructor
2) Parameterized constructor
Default Constructor:
A constructor that have no parameters is known as default constructor.
It is primarily used to initialize the object with default initial values.
When no default constructor is defined by users explicitly, java provides its own
version of default constructor to initialize the object.
Syntax of Default Constructor:
e.g. class Rock
{
Rock()
//default constructor
{}
}
Example of Default Constructor:
class A
{
A()
{
System.out.println(“In A Constructor”);
}
}
class B extends A
{
B()
{
System.out.println(“In B Constructor”);
}
}
class C extends B
{
C()
{
System.out.println(“In C Constructor”);
}
public static void main(String args[])
{
C ob = new c();
}
}
Output:
In A Constructor
In B Constructor
In C Constructor
Parameterized constructor:
A constructor that have parameter is known as parameterized constructor.
Parameter are added to a constructor in the way that they are added to a method,
just declare them inside the parentheses after the constructor’s name.
Parameterized constructor is used to provide different values to the distinct
objects
Example of Parameterized Constructor:
class Student
{
int id;
String name;
Student(int i, String n) // Parameterized Constructor
{
id = i;
name = n;
}
void display()
{
System.out.println(id+""+name);
}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
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 of Constructor Overloading:
class Student
{
int id;
String name;
int age;
Example of Parameterized Constructor:
class Student
{
int id;
String name;
Student(int i, String n) // Parameterized Constructor
{
id = i;
name = n;
}
void display()
{
System.out.println(id+""+name);
}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
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 of Constructor Overloading:
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(111,"Karan");
Student s2 = new Student(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan 25
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
Example of Copy Constructor:
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(111,"Karan");
Student s2 = new Student(s1);
s1.display();
s2.display();
}
}
Overloading Constructor
In addition to overloading normal methods, you can also overload constructor methods. In fact, for
most real-world classes that you create, overloaded constructors
will be the norm, not the exception. To Boxunderstandclass why developed in the preceding chapter.
Following is the latest version of Box:
class Box { double width; double height; double depth;
// This is the constructor for Box. Box(double w, double h, double d)
{ width = w; height = h; depth = d;
}
// compute and return volume double volume() {
return width * height * depth;
}
}
// parameterized constructor 2
Temp(int x)
{
// calls constructor 3
this(5, 15);
System.out.println(x);
}
// parameterized constructor 3
Temp(int x, int y)
{
System.out.println(x * y);
}
75
5
The Default constructor
Rules of constructor chaining :
1. The this() expression should always be the first line of the constructor.
2. There should be at-least be one constructor without the this() keyword
(constructor 3 in above example).
3. Constructor chaining can be achieved in any order.
// parameterized constructor 2
Temp(int x)
{
// invokes default constructor
this();
System.out.println(x);
}
// parameterized constructor 3
Temp(int x, int y)
{
// invokes parameterized constructor 2
this(5);
System.out.println(x * y);
}
default
5
80
// Java program to illustrate Constructor Chaining to
// other class using super() keyword
class Base
{
String name;
// constructor 1
Base()
{
this("");
System.out.println("No-argument constructor of" +
" base
class");
}
// constructor 2
Base(String name)
{
this.name = name;
System.out.println("Calling parameterized constructor"
+ "
of base");
}
}
// parameterized constructor 4
Derived(String name)
{
// invokes base class constructor 2
super(name);
System.out.println("Calling parameterized " +
"constructor of derived");
}
Like any method we can provide access specifier to the constructor. If it’s made
private, then it can only be accessed inside the class.
There are various scenarios where we can use private constructors. The major ones
are
1. Internal Constructor chaining
2. Singleton class design pattern
What is a Singleton class?
As the name implies, a class is said to be singleton if it limits the number of objects
of that class to one.
We can’t have more than a single object for such classes.
Singleton classes are employed extensively in concepts like Networking and
Database Connectivity.
Design Pattern of Singleton classes:
The constructor of singleton class would be private so there must be another way to
get the instance of that class. This problem is resolved using a class member
instance and a factory method to return the class member.
// Java program to demonstrate implementation of Singleton
// pattern using private constructors.
import java.io.*;
class MySingleton
{
static MySingleton instance = null;
public int x = 10;
return instance;
}
}
// Driver Class
class Main
{
public static void main(String args[])
{
MySingleton a = MySingleton.getInstance();
MySingleton b = MySingleton.getInstance();
a.x = a.x + 10;
System.out.println("Value of a.x = " + a.x);
System.out.println("Value of b.x = " + b.x);
}
}
We changed value of a.x, value of b.x also got updated because both ‘a’ and ‘b’
refer to same object, i.e., they are objects of a singleton class
A method in Java is a block of code that, when called, performs specific actions
mentioned in it. For instance, if you have written instructions to draw a circle in the
method, it will do that task. You can insert values or parameters into methods, and
they will only be executed when called. They are also referred to as functions. The
primary uses of methods in Java are:
Creating Method
Considering the following example to explain the syntax of a method −
Syntax
public static int methodName(int a, int b) {
// body
}
Here,
Method definition consists of a method header and a method body. The same is
shown in the following syntax −
Syntax
modifier returnType nameOfMethod (Parameter List) {
// method body
}
The syntax shown above includes −
modifier − It defines the access type of the method and it is optional to use.
returnType − Method may return a value.
nameOfMethod − This is the method name. The method signature consists of the
method name and the parameter list.
Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero parameters.
method body − The method body defines what the method does with the statements.
Example
/** the snippet returns the minimum between two numbers */
publicstaticint minFunction(int n1,int n2){
int min;
if(n1 > n2)
min = n2;
else
min = n1;
return min;}
Method Calling
For using a method, it should be called. There are two ways in which a method is
called i.e., method returns a value or returning nothing (no return value).
The process of method calling is simple. When a program invokes a method, the
program control gets transferred to the called method. This called method then returns
control to the caller in two conditions, when −
return min;
}}
Passing Parameters by Value
While working under calling process, arguments is to be passed. These should be in
the same order as their respective parameters in the method specification. Parameters
can be passed by value or by reference.
Passing Parameters by Value means calling a method with a parameter. Through this,
the argument value is passed to the parameter.
Example
The following program shows an example of passing parameter by value. The values
of the arguments remains the same even after the method invocation.
Live Demo
publicclass swappingExample {
// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = "+ a +" b = "+ b);
}}
This will produce the following result −
Output
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
// for integer
publicstaticint minFunction(int n1,int n2){
int min;
if(n1 > n2)
min = n2;
else
min = n1;
return min;
}
// for double
publicstaticdouble minFunction(double n1,double n2){
double min;
if(n1 > n2)
min = n2;
else
min = n1;
return min;
}}
This will produce the following result −
Output
Minimum Value = 6
Minimum Value = 7.3
Overloading methods makes program readable. Here, two methods are given by the
same name but with different parameters. The minimum number from integer and
double types is the result.