Java Tutorial

Operators

Flow Control

String

Number and Date

Built-in Classes

Array

Class and Object

Inheritance and Polymorphism

Exception Handling

Collections, Generics and Enumerations

Reflection

Input/Output Stream

Annotation

Java Constructor

In Java, a constructor is a special method that is called when an object is instantiated (created). Constructors are used to initialize the object's state (i.e., its instance variables) when an object is created. In this tutorial, we will cover the basics of constructors in Java.

  • Default Constructor

When you don't explicitly define a constructor for a class, Java automatically provides a default constructor. The default constructor initializes the instance variables with their default values (e.g., 0 for numeric types, false for boolean, and null for reference types).

Example:

public class Employee {
    String name;
    int age;
}

public class Main {
    public static void main(String[] args) {
        Employee employee = new Employee(); // Invokes the default constructor

        System.out.println("Name: " + employee.name); // Output: Name: null
        System.out.println("Age: " + employee.age);   // Output: Age: 0
    }
}
  • Custom Constructor

You can define a custom constructor for a class by providing a method with the same name as the class and no return type. You can initialize the object's state with the values passed as parameters to the constructor.

Example:

public class Employee {
    String name;
    int age;

    // Custom constructor
    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class Main {
    public static void main(String[] args) {
        Employee employee = new Employee("John Doe", 30);

        System.out.println("Name: " + employee.name); // Output: Name: John Doe
        System.out.println("Age: " + employee.age);   // Output: Age: 30
    }
}
  • Overloading Constructors

You can provide multiple constructors with different parameter lists in a class. This is called constructor overloading. When an object is created, the appropriate constructor is called based on the number and types of arguments passed.

Example:

public class Employee {
    String name;
    int age;

    // Constructor with no parameters
    public Employee() {
        this.name = "Unknown";
        this.age = 0;
    }

    // Constructor with one parameter
    public Employee(String name) {
        this.name = name;
        this.age = 0;
    }

    // Constructor with two parameters
    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class Main {
    public static void main(String[] args) {
        Employee employee1 = new Employee();
        Employee employee2 = new Employee("Jane Doe");
        Employee employee3 = new Employee("John Doe", 30);

        System.out.println("Employee 1 - Name: " + employee1.name + ", Age: " + employee1.age);
        System.out.println("Employee 2 - Name: " + employee2.name + ", Age: " + employee2.age);
        System.out.println("Employee 3 - Name: " + employee3.name + ", Age: " + employee3.age);
    }
}

In summary, constructors are special methods in Java that are used to initialize the state of an object when it is created. Java provides a default constructor when you don't explicitly define one. You can create custom constructors to initialize the object's state with specific values, and you can overload constructors to provide different initialization options based on the number and types of arguments passed.

  1. Creating constructors in Java classes

    Constructors are special methods used to initialize objects when they are created. They have the same name as the class and do not have a return type.

    public class MyClass {
        // Default constructor
        public MyClass() {
            // Initialization code here
        }
    
        // Other members and methods
    }
    
  2. Default constructor in Java and its significance

    If a class does not explicitly define any constructors, Java provides a default constructor with no parameters. It initializes the object with default values.

    public class MyClass {
        // Default constructor is implicitly provided
    }
    
  3. Parameterized constructors in Java examples

    Parameterized constructors allow you to initialize objects with specific values provided as parameters during object creation.

    public class Person {
        private String name;
        private int age;
    
        // Parameterized constructor
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        // Other members and methods
    }
    
  4. Constructor overloading in Java

    Constructor overloading involves creating multiple constructors in the same class with a different number or type of parameters. This provides flexibility when creating objects.

    public class Rectangle {
        private int length;
        private int width;
    
        // Default constructor
        public Rectangle() {
            // Initialization code
        }
    
        // Parameterized constructor
        public Rectangle(int length, int width) {
            this.length = length;
            this.width = width;
        }
    
        // Other members and methods
    }
    
  5. Initializing objects with Java constructors

    Constructors are called when objects are created using the new keyword. They initialize the object's state.

    public class Main {
        public static void main(String[] args) {
            Person person = new Person("John", 25);
            // Object 'person' is initialized with provided values
        }
    }
    
  6. Calling one constructor from another in Java

    You can call one constructor from another within the same class using the this keyword. This is known as constructor chaining.

    public class MyClass {
        private int value;
    
        // Parameterized constructor
        public MyClass(int value) {
            this.value = value;
        }
    
        // Default constructor calling the parameterized constructor
        public MyClass() {
            this(0); // Calling parameterized constructor with default value
        }
    
        // Other members and methods
    }
    
  7. Constructors in Java interfaces and abstract classes

    Java interfaces and abstract classes can have constructors, but they cannot be instantiated directly. Constructors in interfaces or abstract classes are typically used to initialize their own internal state or call constructors of implementing or extending classes.

    public interface MyInterface {
        // Constructor in interface
        public MyInterface() {
            // Initialization code
        }
    
        // Other members and methods
    }
    
    public abstract class MyBaseClass {
        // Constructor in abstract class
        public MyBaseClass() {
            // Initialization code
        }
    
        // Other members and methods
    }