Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Understanding Constructors in Java

In this lesson, you will learn

  • What is a Constructor
  • Types of Constructors
  • Default Constructor

 

What is Constructor

  • In Java, a constructor is a special type of method that is used to initialize objects of a class.
  • The constructor is called automatically when an instance of a class is created.Their primary job is to set the initial state (values of instance variables) of the object.
  • Constructors have the same name as the class and do not have a return type, not even a void.

 

Signature and Syntax

A constructor’s signature consists of the constructor’s name (which is the same as the class name) and its parameter list (the types and order of parameters).

For example:

public MyClass(int x, String s) { // Signature: MyClass(int, String)
    // ... initialization code ...
}

public MyClass() { // Signature: MyClass() (no parameters)
    // ... initialization code ...
}


 

Types of Constructors in Java

Constructors in Java are of the following types.

Default Constructor

  • A default constructor is a constructor that is automatically provided by the Java compiler if no explicit constructor is defined in a class.
  • It is a no-argument constructor (i.e., it takes no parameters) and initializes the object with default values (e.g., null for objects, 0 for integers, false for booleans, etc.).

 

Syntax

class ClassName {
    // Default constructor (provided by the compiler if no constructor is defined)
    ClassName() {
        // No body or initialization (default values are assigned)
    }
}


 

Key Points about Default Constructor

  1. Automatically Provided: If you do not define any constructor in your class, the Java compiler automatically adds a default constructor.

  2. No Parameters: It takes no arguments.

  3. Default Initialization: It initializes instance variables with their default values:

    • null for object references.

    • 0 for numeric types (int, double, etc.).

    • false for boolean.

    • \u0000 for char.

 

Example 1: Initializing Default Values using Constructor

package ch7;

class RectangleClass {
    // Instance variables
    double length;
    double breadth;

    // Default constructor
    RectangleClass() {
        // Initialize instance variables with default values
        length = 1.0; // Default length
        breadth = 1.0; // Default breadth
    }

    // Method to calculate the area of the rectangle
    double calculateArea() {
        return length * breadth;
    }
}

class RectangleDefault{
	
    public static void main(String[] args) {
        // Creating a rectangle object using the default constructor
        RectangleClass myRect = new RectangleClass();

        // Output the default dimensions and area of the rectangle
        System.out.println("Area: " + myRect.calculateArea());
    }
}

Output

Area: 1.0

 

Note: If no constructor is explicitly defined in a class, the Java compiler automatically provides a default no-argument constructor that initializes the object with default values (e.g., null for objects, 0 for numeric types, false for boolean).

 

Example 2: Book Class – Initializing Default Values using Constructor

package ch7.l5;

class Book {
    String title;
    String author;
    int pages;
 
    // No-argument constructor
    public Book() {
        title = "Untitled";
        author = "Unknown";
        pages = 0;
    }
 
    public void display() {
        System.out.println("Book: " + title +","
        		+ "Author: " + author + ", Pages: " + pages);
    }
}

public class BookDefault {

	public static void main(String[] args) {
		 Book book = new Book();
	     // Output will be "Book: Untitled, Author: Unknown, Pages: 0"
	     book.display(); 
	}
}

Output

Book: Untitled,Author: Unknown, Pages: 0

 

Example 3: Computer Class – Default Constructor

package ch7.l5;

class Computer {
    String processor;
    int ram;
    boolean isGamingPc;
 
    // No-argument constructor
    public Computer() {
        processor = "Intel Core i5";
        ram = 8; // 8 GB RAM
        isGamingPc = false;
    }
 
    public void displaySpecs() {
        System.out.println("Processor: " + processor + ""
        		+ ", RAM: " + ram + "GB, Gaming PC: " + isGamingPc);
    }
}
 
public class ComputerMain {
    public static void main(String[] args) {
        Computer c1 = new Computer();
        Computer c2 = new Computer();
       // Output will be "Processor: Intel Core i5, 
       // RAM: 8GB, Gaming PC: false"
        c1.displaySpecs(); 
         
        //Assigning new values to object i.e. c2
        c2.processor="Intel Core i7";
        c2.ram=16;
        c2.isGamingPc=true;
        c2.displaySpecs();
    }
}

Output

Processor: Intel Core i5, RAM: 8GB, Gaming PC: false
Processor: Intel Core i7, RAM: 16GB, Gaming PC: true

 

Key Points

  • A no-argument constructor initializes an object without requiring any external parameters.
  • It can be used to set default values for the object’s fields.
  • If no constructor is explicitly defined, Java provides a default no-argument constructor.
  • Explicitly defining a no-argument constructor allows for custom initialization of fields.

 

Constructor vs Method

Here’s a table summarizing the differences between a constructor and methods in Java, along with their signatures:

Aspect Constructor Method
Purpose Used to initialize an object when it is created. Used to perform operations or provide behavior for an object.
Name Must have the same name as the class. Can have any valid identifier name (except the class name).
Return Type No return type (not even void). Must have a return type (void if it does not return anything).
Signature ClassName(parameters) returnType methodName(parameters)
Invocation Automatically invoked when an object is created using the new keyword. Explicitly invoked using the object reference or class name (for static).
Overloading Can be overloaded (multiple constructors with different parameters). Can be overloaded (multiple methods with the same name but different parameters).
Inheritance Not inherited by subclasses. Inherited by subclasses (unless private or overridden).
Default If no constructor is defined, a default constructor is provided by the compiler. No default method is provided.
Example public MyClass(int x) { ... } public void myMethod(int x) { ... }

 

Key Points:

  1. Constructor:

    • Used to initialize the state of an object.

    • Cannot be static, final, or abstract.

    • Does not return anything, not even void.

  2. Method:

    • Used to define the behavior of an object.

    • Can be static, final, or abstract.

    • Must have a return type (or void if it does not return anything).

 

 

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

5.0
5.0 out of 5 stars (based on 1 review)
Excellent100%
Very good0%
Average0%
Poor0%
Terrible0%

 

 

April 5, 2025

Easy to understand

 

 

Submit a Review

 

 

Layer 1
Login Categories