0% found this document useful (0 votes)
1 views20 pages

Constructors in Java

Java

Uploaded by

jinni160107
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)
1 views20 pages

Constructors in Java

Java

Uploaded by

jinni160107
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
You are on page 1/ 20

Constructors

In Java, constructors play an important role in


object creation. A constructor is a special block of
code that is called when an object is created. Its
main job is to initialize the object, to set up its
internal state, or to assign default values to its
attributes. This process happens automatically
when we use the "new" keyword to create an
object.
Characteristics of Constructors:
• Same Name as the Class: A constructor has the same
name as the class in which it is defined.
• No Return Type: Constructors do not have any return
type, not even void. The main purpose of a constructor
is to initialize the object, not to return a value.
• Automatically Called on Object Creation: When an
object of a class is created, the constructor is called
automatically to initialize the object’s attributes.
• Used to Set Initial Values for Object
Attributes: Constructors are primarily used to set the
initial state or values of an object’s attributes when it
is created.
• Example: This program demonstrates how a constructor is automatically called
when an object is created in Java.
• class Geeks {

• // Constructor
• Geeks()
• {
• System.out.println("Constructor Called");
• }

• // main function
• public static void main(String[] args)
• {
• Geeks geek = new Geeks();
• }
• }

• 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.
Constructor vs Method in Java
• Constructor :
• Constructors must have the same name as the class name.
• Constructors do not return any type.
• Constructors are called automatically with new keyword.
• Constructors are used to initialize objects.

• Methods :
• Methods can have any valid name.
• Methods have the return type or void if does not return any
value.
• Methods are called explicitly.
• Methods are used to perform operations.
• 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();
Use of Constructors in Java
• Constructors play a very important role, it ensures that an object is
properly initialized before use.
• What happens when we don't use constructors:
• Without constructors:
• Objects might have undefined or default values.
• Extra initialization methods would be required.
• Risk of improper object state
• Think of a Box. If we talk about a box class then it will have some
class variables (say length, breadth, and height). But when it comes
to creating its object (i.e Box will now exist in the computer's
memory), then can a box be there with no value defined for its
dimensions? The answer is No.
So, constructors are used to assign values to the class variables at
the time of object creation, either explicitly done by the
programmer or by Java itself (default constructor).
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 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, 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.
Types of Constructors in Java

• Primarily there are three types of constructors in


Java are mentioned below:

1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
Default Constructor in Java
• A constructor that has no parameters is known as default
constructor. A default constructor is invisible. And if we write
a constructor with no arguments, the compiler does not
create a default constructor. Once you define a constructor
(with or without parameters), the compiler no longer provides
the default constructor. Defining a parameterized constructor
does not automatically create a no-argument constructor, we
must explicitly define if needed. The default constructor can
be implicit or explicit.
• Implicit Default Constructor: If no constructor is defined in a
class, the Java compiler automatically provides a default
constructor. This constructor doesn’t take any parameters and
initializes the object with default values, such as 0 for
numbers, null for objects.
• Explicit Default Constructor: If we define a constructor that takes no
parameters, it's called an explicit default constructor. This
constructor replaces the one the compiler would normally create
automatically. Once you define any constructor (with or without
parameters), the compiler no longer provides the default constructor
for you.
class Geeks{

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

// Driver function
public static void main(String[] args)
{
Geeks hello = new Geeks();
}
}
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: This program demonstrates the use of a parameterized
constructor to initialize an object's attributes with specific values.
• class ABC{

• // data members of the class
• String name;
• int id;

• ABC(String name, int id) {
• this.name = name;
• this.id = id;
• }
• }
• class GFG
• {
• public static void main(String[] args)
• {
• // This would invoke the parameterized constructor
• ABC a1= new ABC("Sweta", 68);
• System.out.println("GeekName: " + geek1.name
• + " and GeekId: " + geek1.id);
• }
• }
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.
• Note: Java does not provide a built-in copy constructor like
C++. We can create our own by writing a constructor that
takes an object of the same class as a parameter and copies
its fields.
• Example: This example, demonstrates how a copy
constructor can be used to create a new object by copying
the values of another object's attributes.
• class Geeks {

• // data members of the class
• String name;
• int id;

• // Parameterized Constructor
• Geeks(String name, int id)
• {
• this.name = name;
• this.id = id;
• }

• // Copy Constructor
• Geeks(Geeks obj2)
• {
• this.name = obj2.name;
• this.id = obj2.id;
• }
• }
• class GFG {
• public static void main(String[] args)
• {
• // This would invoke the parameterized constructor
• System.out.println("First Object");
• Geeks geek1 = new Geeks("Sweta", 68);
• System.out.println("GeekName: " + geek1.name
• + " and GeekId: " + geek1.id);

• System.out.println();

• // This would invoke the copy constructor


• Geeks geek2 = new Geeks(geek1);
• System.out.println(
• "Copy Constructor used Second Object");
• System.out.println("GeekName: " + geek2.name
• + " and GeekId: " + geek2.id);
• }
• }
Constructor Overloading
• Java supports Constructor Overloading in addition to
overloading methods. In Java, overloaded constructor is called
based on the parameters specified when a new is executed.
• When do we need Constructor Overloading?
• Sometimes there is a need of initializing an object in different
ways. This c
• For example, the Thread class has 8 types of constructors. If
we do not want to specify anything about a thread then we
can simply use the default constructor of the Thread class,
however, if we need to specify the thread name, then we may
call the parameterized constructor of the Thread class with a
String args like this:
• Thread t= new Thread (" MyThread ");
• class Box
• {
• double width, height,depth;
• // constructor used when all dimensions
• // specified
• Box(double w, double h, double d)
• {
• width = w;
• height = h;
• depth = d;
• }
• // compute and return volume
• double volume()
• {
• return width * height * depth;
• }
• }
• As we can see that the Box() constructor requires three
parameters. This means that all declarations of Box objects
must pass three arguments to the Box() constructor.
• For example, the following statement is currently invalid:
• Box ob = new Box();
• Since Box() requires three arguments, it’s an error to call it
without them. Suppose we simply wanted a box object
without initial dimension, or want to initialize a cube by
specifying only one value that would be used for all three
dimensions. From the above implementation of the Box class,
these options are not available to us. These types of problems
of different ways of initializing an object can be solved by
constructor overloading.
Example of Constructor Overloading
• class Box {
• double width, height, depth;

• // constructor used when all dimensions


• // specified
• Box(double w, double h, double d)
• {
• width = w;
• height = h;
• depth = d;
• }

• // constructor used when no dimensions


• // specified
• Box() { width = height = depth = 0; }

• // constructor used when cube is created


• Box(double len) { width = height = depth = len; }

• // compute and return volume


• double volume() { return width * height * depth; }
• }
• public class Test {
• public static void main(String args[])
• {
• // create boxes using the various
• // constructors
• Box mybox1 = new Box(10, 20, 15);
• Box mybox2 = new Box();
• Box mycube = new Box(7);

• double vol;

• // get volume of first box


• vol = mybox1.volume();
• System.out.println("Volume of mybox1 is " + vol);

• // get volume of second box


• vol = mybox2.volume();
• System.out.println("Volume of mybox2 is " + vol);

• // get volume of cube


• vol = mycube.volume();
• System.out.println("Volume of mycube is " + vol);
• }
• }

You might also like