0% found this document useful (0 votes)
6 views15 pages

Constructor in Java

This document explains the concept of constructors in Java, including their types such as default, no-argument, and parameterized constructors, along with their syntax and usage. It also covers constructor overloading, allowing multiple constructors in a class with different parameters, and the use of the 'this' keyword to refer to the current object. Examples are provided to illustrate each concept clearly.

Uploaded by

ordinary0360
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views15 pages

Constructor in Java

This document explains the concept of constructors in Java, including their types such as default, no-argument, and parameterized constructors, along with their syntax and usage. It also covers constructor overloading, allowing multiple constructors in a class with different parameters, and the use of the 'this' keyword to refer to the current object. Examples are provided to illustrate each concept clearly.

Uploaded by

ordinary0360
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit -2

Topic: Constructor, Types of constructor, Constructor overloading and


This keyword

Constructor
 A constructor in Java is a special type of method used to initialize objects.
 It is called when an instance of the class is created or say, when an object of
a class is created.
 Whenever an object is created using the new keyword, at least one
constructor is called.

Syntax :

access-modifiers ClassName(list of parameters)


{
//body
}

Example :

public class Test


{
//constructor
public Test()
{
//body
}
public static void main(String[] args)
{
Test t = new Test(); //constructor called automatically when we create
object
}
}
Use of Constructor:

Constructors are used to initialize the object. It means that constructor


assigns the values to the instance variables when an object is created. This
can be done manually by the programmer or automatically by Java using a
default constructor.

Rules for Constructors in Java:

Below are rules for constructors in Java:

1. The constructor must have the same name as that of class name.
2. A constructor does not have a return type (not even void).
3. Constructors can have any access
modifier (public, private, protected or default) but cannot have non-
access modifiers like static, final, abstract etc.
4. The constructor is called automatically when an object is created.

Types of Constructors in Java

There are 3 types of constructors in Java:-

1. Default Constructor
2. No-Args (No Argument) Constructor
3. Parameterized Constructor

1. Default Constructor:

 If programmer does'nt create any constructor, then Java compiler


automatically creates one constructor which is known as default
constructor.
 It initializes an object properties with default values (0, null, false).

Syntax :

class ClassName
{
// Default constructor is automatically provided by Java Compiler
}

Example :

public class Test


{
//here programmer didnt created any constructor, so Java compiler will
create default constructor automatically.

public static void main(String[] args)


{
Test t = new Test(); //default constructor called automatically when we
create object
}
}

Some important points for Default Constructor:

o The access modifier of Default Constructor is as that of class. If a class


is public, the default constructor is public and so on.
o Default Constructor has no parameters.
o Default Constructor calls the superclass constructor (super()).

2. (No Argument) Constructor:

If a programmer creates the constructor without any parameters, then it is


known as No Argument Constructor.
It is used to initialize objects with default values or perform some basic setup.
Syntax :
class ClassName
{
// No-Argument Constructor
ClassName()
{
// Initialization code (if needed)
}
}

Example :

public class Student


{
String name;

// No-Argument Constructor
Student()
{
name = "Deepak"; // Assigning default value
}

void display()
{
[Link]("Student Name: " + name);
}

public static void main(String[] args)


{
Student s1 = new Student(); // Calls no-argument constructor
[Link]();
}
}
Output:

Student Name: Deepak


3. Parameterized Constructor:

 If a programmer creates the constructor with parameters, then it is known


as Parameterized Constructor.
 It is used to:
o Initialize objects with specific values instead of default values.
o Avoid the need for setter methods after object creation.
o Improve code readability by directly assigning values through the
constructor.

Syntax :

class ClassName
{
ClassName(dataType parameter1, dataType parameter2)
{
// Initialization code
}
}

Example :

class Student
{
String name;
int rollno;

// Parameterized Constructor
Student(String n, int rn)
{
name = n;
rollno = rn;
}
void display()
{
[Link]("Name: " + name + ", Roll No.: " + rollno);
}

public static void main(String[] args)


{
Student s1 = new Student("Deepak", 101); // Passing values
[Link](); }
}
Output:

Name: Deepak, Roll No.: 101

Next Topic: Constructor Overloading


Just like methods are overloaded in Java, overloading of constructors is also
possible. We can define multiple constructors within a class and each of them can
have different types of parameters. With the help of constructor overloading,
objects of the class can be created with different kinds of information, we want to
add to it.

Syntax
public class MyClass {
// Constructor with no parameters
public MyClass() {
// Initialization code
}
// Constructor with one parameter
public MyClass(int parameter) {
// Initialization code using the provided parameter
}

// Constructor with multiple parameters


public MyClass(int parameter1, String parameter2) {
// Initialization code using the provided parameters
}
}

Example

public class Employee {


String name;
int id;

// Default constructor
public Employee() {
name="ankit";
id=101;
}

// Parameterized constructor
public Employee(String empName, int empId) {
name = empName;
id = empId;
}

public void display() {


[Link]("Name: " + name + ", ID: " + id);
}

public static void main(String[] args) {


Employee emp1 = new Employee(); // Default constructor
Employee emp2 = new Employee("amit", 102); // Parameterized constructor

[Link]();
[Link]();
}
}

Output:

Name:ankit,ID:101
Name:amit,ID:102

Next Topic: This keyword


In Java, this is a keyword that refers to the current object, the object whose
method or constructor is being executed.

 Use of this Keyword:


1. It is used to refer to the current class instance variable.
2. It is used to refer to the current class method.
3. It is used to refer to the current class constructor.
4. It is used to pass the current class instance as a parameter to the
method.
5. It is used to pass the current class instance as a parameter to the
constructor.
6. It is used to return the current class instance from the method.

1. It is used to refer to the current class instance variable.

Java Program Example 1:

public class ThisDemo


{
int no = 10;
void m1(int no)
{
[Link]("1. no : "+no); // Prints the value of the local
parameter 'no' (method argument)

[Link]("2. no : "+[Link]); //'[Link]' refers to the instance


variable of the current object
}

public static void main(String[] args)


{
ThisDemo obj = new ThisDemo();
obj.m1(20);
}
}
Output:
1. no : 20
2. no : 10

Java Program Example 2:

class Student
{
int id;
String name;

// Constructor with parameters having the same name as instance variables


Student(int id, String name)
{
[Link] = id; // '[Link]' refers to the instance variable
[Link] = name; // 'name' on the right refers to the parameter
}

void display()
{
[Link]("ID: " + id);
[Link]("Name: " + name);
}

public static void main(String[] args)


{
Student s1 = new Student(101, "Amit");
[Link]();
}
}
Output:
ID: 101
Name: Deepak

2. It is used to refer to the current class method.

 Java Program Example:

public class ThisDemo


{
void showMessage()
{
[Link]("Hello from showMessage() method");
}
void display()
{
// Calling another method of the same class using 'this'
[Link](); // Optional: can also call showMessage() directly
[Link]("Inside display() method");
}

public static void main(String[] args)


{
ThisDemo obj = new ThisDemo();
[Link]();
}
}
Output:
Hello from showMessage() method
Inside display() method

3. It is used to refer to the current class constructor.

Java Program Example:

public class ThisDemo


{
// Default constructor
ThisDemo()
{
[Link]("Default constructor called");
}

// Parameterized constructor
ThisDemo(String name)
{
// Calling default constructor using 'this()'
this(); // Must be the first statement in the constructor
[Link]("Hello, " + name);
}
public static void main(String[] args)
{
// Creating object using parameterized constructor
ThisDemo obj = new ThisDemo("Deepak");
}
}
Output:
Default constructor called
Hello, Deepak

4. It is used to pass the current class instance as a parameter to the method.

Java Program Example:

public class ThisDemo


{
void display(ThisDemo obj)
{
[Link]("display() method is called");
}

void call()
{
// Passing current object as argument using 'this'
display(this);
}

public static void main(String[] args)


{
ThisDemo obj = new ThisDemo();
[Link]();
}
}
Output:
display() method is called

5. It is used to pass the current class instance as a parameter to the constructor.

Java Program Example:

class A
{
int value = 10;

A()
{
// Passing current instance of A to B's constructor
B b = new B(this);
}
}

class B
{
// Constructor of class B that accepts a reference to class A
B(A obj)
{
[Link]("Constructor of B is called");
[Link]("Value from class A: " + [Link]);
}
}

public class ThisDemo


{
public static void main(String[] args)
{
A a = new A();
}
}
Output:
Constructor of B is called
Value from class A: 10

6. It is used to return the current class instance from the method.

Java Program Example:

public class ThisDemo


{
int no;

// Method that sets the no and returns the current class instance
ThisDemo setValue(int no)
{
[Link] = no;
return this; // returning current object
}

// Method to display the no


void display()
{
[Link]("Number: " + no);
}

public static void main(String[] args)


{
// Method chaining using returned instance
ThisDemo obj = new ThisDemo();
[Link](100).display(); // chaining method call
}
}
Output:
Number: 100

You might also like