Java Constructor

Java constructor is a special method used to initialize objects. Constructors are called when an object is created, and they have the same name as the class in which they are defined. In this tutorial, we will discuss the basics of Java constructors and how to use them.

Syntax of a Constructor:

A constructor in Java has the following syntax:

public class ClassName{ // instance variables
  public ClassName(parameter_list){
    // code to be executed
  }
}

The constructor has the same name as the class in which it is defined. The access modifier is public, which means that the constructor can be called from anywhere. The parameter list is a list of variables that are passed to the constructor. The code to be executed is enclosed within the curly braces.

Example:

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

In the above example, we have defined a class called Person with two instance variables, name and age. We have also defined a constructor for the Person class that takes two parameters, n and a. The constructor sets the values of the name and age variables to the values passed as arguments.

Creating an Object:

An object can be created by using the new keyword followed by the name of the class and the arguments passed to the constructor. Here is an example of how to create an object of the Person class:

Person p = new Person("John", 30);

In this example, we are creating an object of the Person class and passing the values “John” and 30 to the constructor. The constructor will initialize the name and age instance variables of the object.

Complete code example:

/**
 * 
 * @author Mamun Kayum
 *
 */
public class Person {
	String name;
	int age;

	public Person(String n, int a) {
		name = n;
		age = a;
	}
	
	public void printInfo() {
		System.out.println("Name: "+name+", Age: "+age);
	}
}

/**
 * 
 * @author Mamun Kayum
 *
 */
public class CallerMain {
	public static void main(String[] args) {
		Person person = new Person("John", 50);
		person.printInfo();
	}
}

Default Constructor:

If you do not define a constructor for a class, Java will provide a default constructor with no parameters. The default constructor initializes all instance variables to their default values.

Example:

public class Person{ 
  String name; 
  int age; 
}

In this example, we have defined a class called Person with two instance variables, name and age. Since we have not defined a constructor for the class, Java will provide a default constructor with no parameters. The default constructor will initialize the name and age variables to null and 0, respectively.

Also, see the example code JavaExamples_NoteArena in our GitHub repository. See complete examples in our GitHub repositories.

Follow us on social media
Follow Author