(Java programming Example for Beginners)
Java Constructors
In this tutorial, you’ll learn about Java constructors, how to create and use them, and different types of constructors with the help of examples.
What is a Constructor?
In Java, every class has its constructor that is invoked automatically when an object of the class is created. A constructor is similar to a method but in actual, it is not a method.
A Java method and Java constructor can be differentiated by its name and return type. A constructor has the same name as that of class and it does not return any value. 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.
class Test { void Test() { // method body } }
Here, Test()
has the same name as that of the class. However, it has a return type void
. Hence, it’s a method, not a constructor.
Example: Java Constructor
class Main{
private int x;
// constructor
private Main(){
System.out.println("Constructor Called");
x = 5;
}
public static void main(String[] args){
// constructor is called while creating object
Main obj = new Main();
System.out.println("Value of x = " + obj.x);
}
}
Output:
Constructor Called Value of x = 5
In the above example, we have a private
constructor named Main()
. Inside the main method, we are creating an object named obj of the class.
Main obj = new Main();
During this process, the constructor is called. Hence, the print statement is executed and the variable x is initialized.
Types of Constructor
In Java, constructors can be divided into 3 types:
- No-Arg Constructor
- Default Constructor
- Parameterized Constructor
No-Arg Constructor
A Java constructor may or may not have any parameters (arguments). If a constructor does not accept any parameters, it is known as a no-arg constructor. For example,
private Constructor(){
// body of constructor
}
Example of no-arg constructor
class Main{
int i;
// constructor with no parameter
private Main(){
i = 5;
System.out.println("Object created and i = " + i);
}
public static void main(String[] args){
// calling the constructor without any parameter
Main obj = new Main();
}
}
Output:
Object created and i = 5
Here, the constructor Main()
does not accept any parameters.
Did you notice that the access modifier of the Main() constructor is private?
This is because the object is instantiated from within the same class. Hence, it can access the constructor.
However, if the object was created outside of the class, you have to declare the constructor public
to access it. For example:
class Company{
String domainName;
// public constructor
public Company(){
domainName = "programing.com";
}
}
public class Main{
public static void main(String[] args){
// object is created in another class
Company companyObj = new Company();
System.out.println("Domain name = "+ companyObj.domainName);
}
}
Output:
Domain name = programing.com
Default Constructor
If you do not create any constructors, the Java compiler will automatically create a no-argument constructor during run-time. This constructor is known as the default constructor. The default constructor initializes any uninitialized instance variables with default values.
Type | Default Value |
---|---|
boolean |
false |
byte |
0 |
short |
0 |
int |
0 |
long |
0L |
char |
u0000 |
float |
0.0f |
double |
0.0d |
object |
Reference null |
Example: Default Constructor
class DefaultConstructor{
int a;
boolean b;
public static void main(String[] args){
// A default constructor is called
DefaultConstructor obj = new DefaultConstructor();
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
Output:
a = 0 b = false
In the above program, we have not initialized the value of both the variables, a and b. However, when we create an object of the class, we can see in the output that the values are initialized with some values.
It is because the Java compiler has automatically created a default constructor. The constructor will initialize the value of variables a and b with default values 0
and false
.
The above program is equivalent to:
class DefaultConstructor{
int a;
boolean b;
// a private constructor
private DefaultConstructor(){
a = 0;
b = false;
}
public static void main(String[] args){
// call the constructor
DefaultConstructor obj = new DefaultConstructor();
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
Output:
a = 0 b = false
Parameterized Constructor
Similar to methods, we can pass parameters to a constructor. Such constructors are known as a parameterized constructor. For example,
private Constructor (arg1, arg2, ..., argn){
// constructor body
}
Example: Parameterized constructor
class Vehicle{
int wheels;
// constructor accepting single value
private Vehicle(int wheels){
this.wheels = wheels;
System.out.println(wheels + " wheeler vehicle created.");
}
public static void main(String[] args){
// calling the constructor by passing single value
Vehicle v1 = new Vehicle(2);
Vehicle v2 = new Vehicle(3);
Vehicle v3 = new Vehicle(4);
}
}
Output:
2 wheeler vehicle created. 3 wheeler vehicle created. 4 wheeler vehicle created.
In the above example, we have a constructor named Vehicle()
. The constructor accepts a single parameter named wheels.
Here, while creating objects, we are passing arguments to the constructor. And, based on the argument, it is generating the output.
Constructors Overloading in Java
Similar to method overloading, we can also overload constructors in Java.
In constructor overloading, there are two or more constructors with different parameters. For example,
class Company{
String domainName;
// constructor with no parameter
public Company(){
this.domainName = "default";
}
// constructor with single parameter
public Company(String domainName){
this.domainName = domainName;
}
public void getName(){
System.out.println(this.domainName);
}
public static void main(String[] args){
// calling the constructor with no parameter
Company defaultObj = new Company();
// calling the constructor with single parameter
Company programizObj = new Company("programiz.com");
defaultObj.getName();
programizObj.getName();
}
}
Output:
default programiz.com
In the above example, we have two constructors: public Company(
) and public Company(String domainName)
.
Here, both the constructor are initializing the variable domainName with different values. Hence, based on the value we want, we can call the constructor from the main()
method.
Note that, we have used this
keyword to specify the variable of the class.
Important Notes
- Constructors are invoked implicitly when you instantiate objects.
- The two rules for creating a constructor are:
- The name of the constructor should be the same as that of class.
- 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 to0
- Constructor types:
- No-Arg Constructor – a constructor that does not accept any arguments
- Default Constructor – a constructor that is automatically created by the Java compiler if it is not explicitly defined.
- Parameterized constructor – a constructor that accepts arguments
- A constructor cannot be abstract or static or final.
- A constructor can be overloaded but can not be overridden.
Java tutorials for Beginners – Java Constructors
Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.