DEV Community

Divya Divya
Divya Divya

Posted on

Constructor in Java

What is Constructor:

  • Constructor is a Special method in Java.
  • When object is create , it's automatically called.
  • Constructor it helps to object set the initial value.
  • Giving an initial value to a variable when it is created.

Default Constructor:

  • Default Constructor is no arguments in the constructor.
  • You don't define the constructor , Java is given the default constructor.
  • If you do NOT write any constructor → the compiler will automatically create a default (no-argument) constructor.

  • Purpose of constructor provides default values (0,null).

Example:

 class Person{
     String name;
     int age;

public static void main(String[] args){
    Person s1=new Person();

System.out.println(s1.name);
System.out.println(s1.age);
}
 }
Enter fullscreen mode Exit fullscreen mode

Output:

Parameterized Constructor

  • A parameterized constructor is a special method in Java.
  • It is used to set values when an object is created.
  • Unlike a default constructor (which gives common values like 0 or null).
  • a parameterized constructor lets you pass your own values.
  • You can give values while creating the object.
  • It sets those values to the object’s variables (fields)

Output

 class Person{
     String name;
     int age;



public Person(String a , int b){
    name=a;
    age=b;
}

public static void main(String[] args){
    Person s1=new Person("Divya" , 21);

System.out.println(s1.name);
System.out.println(s1.age);
}
 }
Enter fullscreen mode Exit fullscreen mode

Output

No-Arguments Constructor

  • This Constructor created by programmer
  • It has a no parameters
  • It helps to some specific code run , at the time of object creation
  • It is used to set a common values and message print.
  • Purpose of Zero argument constructor , assigns custom starting values.

Example

public class Person {

    public Person() {
        System.out.println("No-argument");
    }

    public static void main(String[] args) {
        Person s1 = new Person();
    }
}

Enter fullscreen mode Exit fullscreen mode

Output

Top comments (0)