Constructor in Java


A constructor in java is a block of code similar to a method that’s called when an instance of an object is created. People often refer constructor as a type of method in java. Though a method and a constructor are the same , they also have their differences and the differences are:
• A constructor doesn’t have a return type.
• The name of the constructor must be the same the name of the classs.
• Constructors are taken as members of a class.
The syntax of a constructor is “public Name of the class( )”. The parenthesis the constructor has might take a parameter which is used to initialize attributes and it can just be left empty and this will lead to the three types of constructors and they are :
1. Default Constructor
2. No-arg Constructor
3. Parameterized constructor

Default Constructor

If you do not implement any constructor in your class, Java compiler inserts a default constructor into your code on your behalf.

No-arg Constructor

Constructor with no arguments is known as no-arg constructor. This is when you create your constructor without writing any arguement.

Parameterized Constructor

This is a type of constructor with parameters.

How does a constructor work

To understand how a constructor works follow the two programs below

First Program


public class GradeCard{
private String courseName;// creating an instance variable
//creating a constructor
public GradeCard(String name){
 courseName= name;
}
public void setCourseName(String name){
 courseName= name;
}
public String getCourseName( ){
	return courseName;
}
public void displayMessage(  ){
  System.out.printf("%s\n"  , getCourseName( ));
}
	
}

Note: This above program is a Parameterized constructor which means it has a parameter which means when initializing the object you have to use an argument.

Second Program


import java.util.Scanner;
public class GradeCardTest{
public static void main(String [] args){
// creating an object out of class Scanner
Scanner input= new Scanner(System.in);
System.out.print("Enter your first course: ");
String nameOfCourse1= input.nextLine( );
// the new keyword here creates the object of  the class of the first program and invokes the constructor to initialize the newly created object 
GradeCard myGradeCard1= new GradeCard(nameOfCourse1); // you can see the constructor carrys an argument 
 myGradeCard1.setCourseName(nameOfCourse1);
myGradeCard1.displayMessage( );

	}
}

Output:

Enter your First Course: CSC101

Note that is in the second program that the program will run because that is where the execution takes place.
click on the link to read more on constructor
http://www.solarexinstitute.com.ng/constructor-in-java/