Java Constructors - 14 - 10 - 2023
Java Constructors - 14 - 10 - 2023
What is a Constructor?
A constructor in Java is similar to a method that is invoked when an object of
the class is created.
Unlike Java methods, a constructor has the same name as that of the class
and does not have any return type. For example,
class Test {
Test() {
// constructor body
Here, Test() is a constructor. It has the same name as that of the class and
doesn't have a return type.
// constructor
Main() {
System.out.println("Constructor Called:");
name = "Programiz";
}
Output:
Constructor Called:
The name is Programiz
Here, when the object is created, the Main() constructor is called. And, the
value of the name variable is initialized.
Types of Constructor
1. No-Arg Constructor
2. Parameterized Constructor
3. Default Constructor
int i;
Output:
Constructor is called
Value of i: 5
// public constructor
public Company() {
name = "Programiz";
}
}
class Main {
public static void main(String[] args) {
Output:
String languages;
Output:
Here, we are passing the single value to the constructor. Based on the
argument passed, the language variable is initialized inside the constructor.
3. Java Default Constructor
If we do not create any constructor, the Java compiler automatically create a
no-arg constructor during the execution of the program. This constructor is
called default constructor.
int a;
boolean b;
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
Run Code
Output:
Default Value:
a = 0
b = false
The default constructor initializes any uninitialized instance variables with default values.
boolean false
byte 0
short 0
int 0
long 0L
char \u0000
float 0.0f
double 0.0d
In the above program, the variables a and b are initialized with default
value 0 and false respectively.
The above program is equivalent to:
class Main {
int a;
boolean b;
Main() {
a = 0;
b = false;
}
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
Run Code
The output of the program is the same as Example 5.
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 .
String language;
obj1.getName();
obj2.getName();
}
}
Run Code
Output:
language) . Here, both the constructor initialize the value of the variable
language with different values.
Based on the parameter passed during object creation, different constructors
are called and different values are assigned.