java constructors program

Constructors Program in Java


What is a constructor?

A constructor is a special method of a class and it is present under that class, and it is used to initializing the variables of that class, it is defined with the same name as the class.


What is the use of the constructor?

It is responsible for initialization variables when the object/instance of that class is created.


How we can use this constructor?

We have 2 types of constructors –

1.   With Parameters

2.   Without Parameters


There is two way of defining a constructor:

1.   Implicit Constructor

2.   Explicit Constructor


An implicit Constructor is a constructor which is created by the compiler, not by the programmer.

The implicit constructor is a parameterless constructor and is also known as Default Constructor.

Default Constructor means that when an instance/object of a class is created then the compiler creates the constructor with the same name of that class.

Explicit constructors are the constructors, which are defined by the programmer and they can be parameterless or with parameters.


Need/Use of constructor in oops –

Whenever an object or a variable is created it cannot be used directly as it requires some value to store or some default value to store in the memory performing some task/action in the program. If the value is not given by the programmer or no values are set for the variables/instances then it simply used the default values. So, who provides the default values? – it is provided by the constructor. When the object/instance of a class is created the constructor comes into the action to provide the values to the variables.


Is it necessary to use the constructor?

Yes, if you don’t create a constructor then a default one is created by the compiler.


Example – Default Constructors Program in Java

public class DC {
  int a; 

  public static void main(String[] args) {
    DC d = new DC();
    System.out.println(d.a); 
  }
}
//the default constructor is created by the Complier


Output – 0 (zero)


Example- Parameterless Constructors Program in Java

public class PC {
  int a; 
public PC(){
 a = 10;
}

  public static void main(String[] args) {
    PC d = new PC();
    System.out.println(d.a); 
  }
}
//the Explicit constructor without parameter

Output – 10


Example- Parameterized Constructors Program in Java

public class WPC {
  int a; 
public WPC(int b){
 a = b;
}

  public static void main(String[] args) {
    WPC d = new WPC(100);
    System.out.println(d.a); 
  }
}
//the Explicit constructor with parameter

Output –  100


See other Questions also- 

1. Java Data Types Programs