0% found this document useful (0 votes)
7 views

Constructors

Uploaded by

snehasahu0444
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Constructors

Uploaded by

snehasahu0444
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Java Constructors

A constructor in Java is a special method that is used to initialize objects. The constructor is called
when an object of a class is created.

Unlike Java methods, a constructor has the same name as that of the class and does not have any return
type.

It can be used to set initial values for object attributes.

Note: It is not necessary to write a constructor for a class. It is because the java compiler creates a default
constructor (constructor with no arguments) if your class doesn’t have any.

class Main {
private String name;

// constructor
Main() {
System.out.println("Constructor Called:");
name = "Hello Students";
}

public static void main(String[] args) {

// constructor is invoked while


// creating an object of the Main class
Main obj = new Main();
System.out.println("The name is " + obj.name);
}
}

Output:
Constructor Called:
Hello Students

Public Constructor:

// Create a Main class


class Temp{
int x;
// Create a class constructor for the Main class
public Temp() {
x = 5;
}
}
public class Main {
public static void main(String[] args) {
Temp myObj = new Temp();
System.out.println(myObj.x);
}}
How Java Constructors are Different From Java Methods?

 Constructors must have the same name as the class within which it is defined it is not necessary for
the method in Java.
 Constructors do not return any type while method(s) have the return type or void if does not return
any value.
 Constructors are called only once at the time of Object creation while method(s) can be called any
number of times.

Now let us come up with the syntax for the constructor being invoked at the time of object or
instance creation.

class Geek
{
.......

// A Constructor
Geek() {
}

.......
}

// We can create an object of the above class using the below statement. This
statement calls above constructor.

Geek obj = new Geek();

When Constructor is called?

Each time an object is created using a new() keyword, at least one constructor (it could be the default
constructor) is invoked to assign initial values to the data members of the same class. Rules for
writing constructors are as follows:

 The constructor(s) of a class must have the same name as the class name in which it resides.
 A constructor in Java can not be abstract, final, static, or Synchronized.
 Access modifiers can be used in constructor declaration to control its access i.e which other class can
call the constructor.

So by far, we have learned constructors are used to initialize the object‟s state. Like methods, a
constructor also contains a collection of statements(i.e. instructions) that are executed at the time of
Object creation.

Remember: Does constructor return any value?

There are no “return value” statements in the constructor, but the constructor returns the current class
instance. We can write „return‟ inside a constructor.

Important Notes on Java Constructors


 Constructors are invoked implicitly when you instantiate objects.
 The two rules for creating a constructor are:
The name of the constructor should be the same as the class.
A Java constructor must not have a return type.
 If a class doesn't have a constructor, the Java compiler automatically creates a default
constructor during run-time. The default constructor initializes instance variables with
default values. For example, the int variable will be initialized to 0
 Constructor types:
No-Arg Constructor - a constructor that does not accept any arguments
Parameterized constructor - a constructor that accepts arguments
Default Constructor - a constructor that is automatically created by the Java compiler if it is
not explicitly defined.
 A constructor cannot be abstract or static or final.
 A constructor can be overloaded but can not be overridden.

Types of Constructors in Java


Now is the correct time to discuss the types of the constructor, so primarily there are three types of
constructors in Java are mentioned below:

 Default Constructor
 Parameterized Constructor
 Copy Constructor

1. Default Constructor in Java

A constructor that has no parameters is known as default the constructor. A default constructor is
invisible. And if we write a constructor with no arguments, the compiler does not create a default
constructor. It is taken out. It is being overloaded and called a parameterized constructor. The default
constructor changed into the parameterized constructor. But Parameterized constructor can‟t change
the default constructor.

Example:

// Java Program to demonstrate


// Default Constructor
import java.io.*;

// Driver class
class GFG {

// Default Constructor
GFG() { System.out.println("Default constructor"); }

// Driver function
public static void main(String[] args)
{
GFG hello = new GFG();
}
}

Output:
Default constructor

2. Parameterized Constructor in Java

A constructor that has parameters is known as parameterized constructor. If we want to initialize


fields of the class with our own values, then use a parameterized constructor.

Example:
// Java Program for Parameterized Constructor
import java.io.*;
class Geek {
// data members of the class.
String name;
int id;
Geek(String name, int id)
{
this.name = name;
this.id = id;
}
}
class GFG {
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
Geek geek1 = new Geek("avinash", 68);
System.out.println("GeekName :" + geek1.name
+ " and GeekId :" + geek1.id);
}
}
Output
GeekName :avinash and GeekId :68

Example2:
// Java Program to illustrate constructor overloading
// using same task (addition operation ) for different
// types of arguments.

import java.io.*;

class Geek {
// constructor with one argument
Geek(String name)
{
System.out.println("Constructor with one "
+ "argument - String : " + name);
}

// constructor with two arguments


Geek(String name, int age)
{

System.out.println(
"Constructor with two arguments : "
+ " String and Integer : " + name + " " + age);
}

// Constructor with one argument but with different


// type than previous..
Geek(long id)
{
System.out.println(
"Constructor with one argument : "
+ "Long : " + id);
}
}

class GFG {
public static void main(String[] args)
{
// Creating the objects of the class named 'Geek'
// by passing different arguments
// Invoke the constructor with one argument of
// type 'String'.
Geek geek2 = new Geek("Shikhar");

// Invoke the constructor with two arguments


Geek geek3 = new Geek("Dharmesh", 26);

// Invoke the constructor with one argument of


// type 'Long'.
Geek geek4 = new Geek(325614567);
}
}

Output:
Output
Constructor with one argument - String : Shikhar
Constructor with two arguments : String and Integer : Dharmesh 26
Constructor with one argument : Long : 325614567

3. Copy Constructor in Java

Unlike other constructors copy constructor is passed with another object which copies the data
available from the passed object to the newly created object.

A copy constructor is a special type constructor which creates an object using another object of the same
class. In return, it gives a copy of an already created object that is copied.

Example 1:

class Rectangle
{
private double length;
private double breadth;

//constructor to initialize variables


Rectangle(double l, double b)
{
length = l;
breadth = b;
}

//copy constructor
Rectangle(Rectangle rect)
{
System.out.println("Copy Constructor Invoked!!");
length = rect.length;
breadth = rect.breadth;
}
//method to return area
double calculateArea()
{
return length*breadth;
}
}

class Rectangle_Main{

public static void main(String[] args)


{
Rectangle rec1 = new Rectangle(10,20);
System.out.println("Area of the First Rectangle "+ rec1.calculateArea());

//passing the parameter to the copy constructor


Rectangle rec2 = new Rectangle(rec1);
System.out.println("Area of the Second Rectangle "+ rec2.calculateArea());
}
}Output:
Area of the First Rectangle 200.0
Copy Constructor Invoked!!
Area of the Second Rectangle 200.0

Example 2:
// Java Program for Copy Constructor
import java.io.*;

class Student {
// data members of the class.
String name;
int id;

// Parameterized Constructor
Student (String n, int a)
{
name = n;
id = a;
}

// Copy Constructor
Student (Student obj2)
{
name = obj2.name;
id = obj2.id;
}
}
class College {
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
System.out.println("First Object");
Student S1 = new Student ("avinash", 68);
System.out.println("Name :" + S1.name + " and Id :" + S1.id);

System.out.println();

// This would invoke the copy constructor.


Student S2 = new Student (S1);
System.out.println("Copy Constructor used Second Object");
System.out.println("Name :" + S2.name + " and Id :" + S2.id);
}
}

Output:
First Object
GeekName :avinash and GeekId :68

Copy Constructor used Second Object


GeekName :avinash and GeekId :68
Constructor Overloading in Java
In Java, a constructor is just like a method but without return type. It can also be overloaded like Java
methods.

Constructor overloading in Java is a technique of having more than one constructor with different
parameter lists. They are arranged in a way that each constructor performs a different task. They are
differentiated by the compiler by the number of parameters in the list and their types.

Similar to Java method overloading, we can also create two or more constructors with different
parameters. This is called constructors overloading.

Example of Constructor Overloading

1. //Java program to overload constructors


2. class Student5{
3. int id;
4. String name;
5. int age;
6. //creating two arg constructor
7. Student5(int i,String n){
8. id = i;
9. name = n;
10. }
11. //creating three arg constructor
12. Student5(int i,String n,int a){
13. id = i;
14. name = n;
15. age=a;
16. }
17. void display(){System.out.println(id+" "+name+" "+age);}
18.
19. public static void main(String args[]){
20. Student5 s1 = new Student5(111,"Karan");
21. Student5 s2 = new Student5(222,"Aryan",25);
22. s1.display();
23. s2.display();
24. }
25. }

Output:

111 Karan 0
222 Aryan 25

You might also like