Objective

On this section we will be discussing about default constructor. Before going to the example code, let’s describe first what is a constructor.  A constructor is basically a special type of method which is automatically been called when the class is instantiated. The following rules must be followed in defining a constructor

  • method name is the same as class name
  • there would be no return type.
  • Constructors can use any access modifier, including private. However when we declare a private modifier then the constructor can only be used within the same class. Using private modifier is helpful when we don’t want to expose this constructor and it’s meant only to be used in constructor chaining or of the same purpose.
  • Constructors can be overloaded too which means we can have multiple constructors but with different signatures.
  • There are two types of constructors, the default constructor and the parameterized constructor. On this document we will be interested on the default constructor which is the no-arg constructor.
  • Constructors whether  implicitly declared to call super(), it will always call the it.
  • Even you don’t declare a default constructor, every time an object is instantiated the default constructor will be called.

Default Constructor Example

Below is the Student class. Basically this class just return a default student name “Steve Smith” when the class is initialized with a default constructor. On later examples, I will be showing later on how to use the Student class.

package com.javatutorialhq.java.staticexamples;

/*
 * This a student class
 * that initialize a student object
 */

public class Student {
	
	// declare student name
	private String firstName = "Steve";
	private String lastName = "Smith";
	private String fullName = "";
	
	// default constructor
	public Student(){
		// initialize a default Student name
		fullName = firstName + " " + lastName;	
		
	}
	
	// return student name
	public String getName(){	
		return fullName;
	}

}

This example is basically the Main class that initialize the Student object.

package com.javatutorialhq.java.staticexamples;
/*
 * A Main class to instantiate the class Student
 */

public class Main {

	public static void main(String[] args) {

		Student student = new Student();
		System.out.println(student.getName());
	}

}

Sample Output

Running the above code will give the following output

Steve Smith