Java Parameterized Constructor

Java Parameterized Constructor

A parameter refers to a value that one adds or modify when issuing a command so that the command accomplished its task.

Constructors with parameters are known as Java Parameterized constructors. It is used to provide different values to distinct objects.

A default constructor does not have any parameter, but if you need, a constructor can have parameters. This helps you to assign initial value to an object at the time of its creation as shown in the following example.

Parameterized Constructor Example 1:



Output :

var is: 10
var is: 100

Parameterized Constructor Example 2:



Output :

 2 wheeler vehicle created.
 3 wheeler vehicle created.
 4 wheeler vehicle created.

Java Default Constructor?

Default constructor in Java is a constructor with no parameters. The default constructor does nothing, but it enables all variables that are not initialized in their declaration to assume default values as follows:

  • Numeric data members are set too.
  • Boolean data memberrs are set to false.
  • String are set to null.

In practical programs, we often need to initialize the various data elements of the different object with different values when they are created. This can be achieved by passing the arguments to the constructor functions when the object is created.

Note: Even if we do not define any constructor explicitly, the compiler will automatically provide a default constructor implicitly.

Default Constructor Syntax:

   public class MyClass{
   //This is the constructor
   MyClass(){
   }
   ..
}

Java Default Constructor Example 1:

class NoArgCtor {
int i;
// constructor with no parameter
 private NoArgCtor(){
 i = 5;
 System.out.println("Object created and i = " + i);
 }
 public static void main(String[] args) {
NoArgCtor obj = new NoArgCtor();
}
}

Output :

Object created and i = 5

Java Default Constructor Example 2:

class DefaultConstructor {
int a;
boolean b;
private DefaultConstructor() {
a = 0;
b = false;
}
public static void main(String[] args) {
DefaultConstructor obj = new DefaultConstructor();
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}

Output :

a = 0
b = false