Important Notes on Java Constructors
Constructors are invoked implicitly when you instantiate objects.
The two rules for creating a constructor are:
1. The name of the constructor should be the same as the class.
2. 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 cannot be overridden.
1
Constructor overloading
Constructor overloading is a concept of having more than one
constructor with different parameters list, in such a way so that each
constructor performs a different task.
Need of constructor overloading
A constructor is a method in a class that is called as soon as the
object of that class is created. Sometimes, we are required to
initialize objects in different forms. This can be achieved using
constructor overloading.
For example, sometimes we need to initialize an object with
default values, and other times we need to declare them with
specific values. In these cases, constructor overloading comes
handy.
Consider a program below that creates a class Rectangle having
three constructors:
Rectangle()
2
Rectangle(length)
Rectangle(length, breadth
// Creating a class
class Rectangle
{
int length, breadth;
// Default constructor
Rectangle( )
{
length = 0;
breadth = 0;
}
// Parameterised constructor
// Containing only length
Rectangle(int length)
{
this.length = length;
breadth = 1;
}
// Parameterised constructor
// Containing length and breadth both
Rectangle(int length, int breadth)
{
this.length = length;
this.breadth = breadth;
}
// Print the area of the rectangle
3
void area()
{
System.out.println(length * breadth);
}
class HelloWorld {
public static void main(String[] args) {
// Creating an object
// by calling default constructor
Rectangle rect1 = new Rectangle();
rect1.area();
// Creating an object
// by calling constructor having only length
// as argument
Rectangle rect2 = new Rectangle(10);
rect2.area();
// Creating an object
// by calling constructor having both length
// and breadth as argument
Rectangle rect3 = new Rectangle(10, 20);
rect3.area();
}
}
4
5