Sitemap

Constructors in Java Example-

1 min readFeb 24, 2024

--

What are Constructors?

In Java, a constructor is a special type of method that is invoked when an object is instantiated or created. The purpose of a constructor is to initialize the state of an object. Constructors are defined within the class and have the same name as the class.

  1. Default Constructor: If no constructor is defined in a class, Java will provide a default constructor without any parameters.

Example:

// Default Constructor Example

package Constructors;

public class ConstructorsExample2 {

ConstructorsExample2()

{

System.out.println(“Default Constructor”);

}

public static void main(String[] args) {

ConstructorsExample2 a= new ConstructorsExample2();

}

}

2. Parameterized Constructor: Constructors can be initialized with parameters, allowing for various ways of initializing objects based on the provided values.

Get Dhiraj Singh’s stories in your inbox

Join Medium for free to get updates from this writer.

//Parameterized Constructor

package Constructors;

public class ParameterizedConst {

ParameterizedConst(String name)

{

System.out.println(“This is single argument:”+name);

}

ParameterizedConst(String name, int age)

{

System.out.println(“This is single argument:”+name+” “+age);

}

public static void main(String[] args) {

ParameterizedConst p = new ParameterizedConst(“RamaKrishnana”);

ParameterizedConst p1 = new ParameterizedConst(“Talishka”,90);

}

}

--

--