Java Objects and Classes Constructors

Learning objective: By the end of this lesson, students will be able to instantiate objects from classes and set default values for their variables.

Objects in Java

An object is an instance of a class. Objects represent real-world entities with attributes (properties) and behaviors (methods).

Instantiating an object

We use the new keyword to create an object from a class.

Syntax: ClassName objectName = new ClassName();

Once instantiated, we can access and modify the properties and call methods (defined in the class) by using the dot (.) operator.

Example:

class Car {
    // Properties (Instance Variables)
    String brand;
    int speed;

    // Method
    void displayInfo() {
        System.out.println("Brand: " + brand + ", Speed: " + speed + " km/h");
    }
}

public class Main {
    public static void main(String[] args) {
        // Step 1: Instantiate the object
        Car myCar = new Car();

        // Step 2: Access and modify properties
        myCar.brand = "Toyota";
        myCar.speed = 120;

        // Step 3: Call the method
        myCar.displayInfo(); // Output: Brand: Toyota, Speed: 120 km/h
    }
}

Constructors

A constructor in Java is a special method used to initialize an object when it is created. It is called automatically when an object of a class is instantiated using the new keyword. The main purpose of a constructor is to set initial values for the fields of an object.

Characteristics of constructors

  1. The constructor must have the same name as the class.
  2. Constructors do not have a return type, not even void.
  3. Constructors are invoked automatically when an object is created.
  4. Like regular methods, constructors can be overloaded to accept different sets of parameters.

Example:

public class Student {
    public Student() {
        System.out.println("Constructor called!");
    }
}

Types of constructors

  1. Default constructor: Java provides a default constructor if no other constructors are defined. Default constructors take no arguments. For example:

    public class Student {
        public Student() {
            System.out.println("Default Constructor");
        }
    }
    
  2. Parameterized constructor: Any constructor that takes arguments to initialize fields of the object is called a parameterized constructor. For example:

     public class Student {
         String name;
         int age;
    
         public Student(String name, int age) {
             this.name = name;
             this.age = age;
         }
     }