Constructors in Java
Constructors in Java
• // 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
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();
• double vol;