←Back to Subject
Notes
Notes
Study material and explanations
Diagrams
Diagrams
Visualize concepts easily
Mnemonics
Mnemonics
Tricks to remember faster
One Night Prep
One Night Prep
Short and focused revision
Revision
Revision
Quick summary and key points
Important Questions
Important Questions
Practice most relevant questions
Notes

Classes, Objects, Methods & Constructors (Default, Parameterized & Copy)

Study material and explanations for Unit 2

Classes, Objects, Methods & Constructors in Java

1. Defining a Class, Variables, and Methods

In Java, a Class is a user-defined blueprint or template from which individual Objects (Instances) are created. A class combines two things into a single unit:

  1. Fields (Instance Variables / Attributes): Represent the state or data of the object.
  2. Methods (Member Functions): Represent the behavior or actions that operate on that data.

Syntax for Defining a Class

class ClassName {
    // 1. Instance Variables (Fields)
    dataType variable1;
    dataType variable2;

    // 2. Constructors (for initializing fields)
    ClassName() { ... }

    // 3. Methods (Behaviors)
    returnType methodName(parameters) {
        // method body
    }
}

2. Creating Objects (Instantiation) in Java

An Object is a runtime instance of a class that occupies actual memory in the Heap. Creating an object from a class is called Instantiation and involves two steps using the new keyword:

Figure 2.1: Two Steps of Creating an Object in Java (Student s1 = new Student();)
1. DeclarationStudent s1; (Creates reference on Stack)
→
2. Instantiation (new)Allocates memory for object on Heap
→
3. InitializationCalls Constructor Student() to set fields
  1. Declaration (Student s1;): Declares a reference variable s1 in Stack memory that initially holds null.
  2. Instantiation & Initialization (s1 = new Student();): The new operator dynamically allocates memory for a new Student instance in Heap memory, invokes the constructor to initialize fields, and returns the Heap memory address to s1.

Accessing Fields and Methods (The Dot . Operator)

Once an object is created, we use the dot operator (.) with the object reference to access its variables and methods:

s1.rollNo = 101;
s1.displayDetails();

3. Constructors in Java

A Constructor is a special member method of a class that is automatically called by the JVM at the exact moment an object is created using the new keyword. Its primary job is initializing the fields (instance variables) of the newly created object.

4 Golden Rules of a Constructor

  1. The constructor name must be 100% identical to the Class Name.
  2. A constructor must NOT have any return type, not even void! (If you write void Student(), Java treats it as a normal method, not a constructor).
  3. It is called automatically only once per object creation (new ClassName()).
  4. A constructor cannot be abstract, static, or final.

4. Types of Constructors in Java (Including Copy Constructor)

In Java, constructors are divided into 3 types:

Figure 2.2: Three Types of Constructors in Java
1. Default (No-Arg) Constructor
Takes no arguments; initializes fields with default or fixed starting values
2. Parameterized Constructor
Accepts arguments to initialize each object with custom user-supplied values
3. Copy Constructor
Accepts another object of the SAME class as a parameter and copies its fields

1. Default (No-Argument) Constructor

  • A constructor that accepts zero parameters.
  • Implicit Default Constructor: If you do not write any constructor in your class, the Java compiler automatically inserts a hidden no-arg constructor that initializes fields to their default values (0, 0.0, false, null).
  • Explicit No-Arg Constructor: Written by the programmer to set custom initial values.

2. Parameterized Constructor

  • A constructor that accepts one or more parameters. It allows us to initialize different objects with different values right at the time of creation: new Student(101, "Rohan").

3. Copy Constructor in Java

  • What is a Copy Constructor? A constructor that initializes a new object using the values of an already existing object of the same class (Student(Student other)).
  • Important Note: Unlike C++, Java does not provide a built-in default copy constructor. We must define it ourselves by passing an object reference of the same class as a parameter!

Complete Program Demonstrating All 3 Constructors & Constructor Overloading

class Student {
    int rollNo;
    String name;
    double cgpa;

    // 1. Default (No-Arg) Constructor
    Student() {
        rollNo = 0;
        name = "Not Assigned";
        cgpa = 0.0;
    }

    // 2. Parameterized Constructor (Field Initialization)
    Student(int r, String n, double c) {
        rollNo = r;
        name = n;
        cgpa = c;
    }

    // 3. Copy Constructor (Takes another Student object 's' as parameter)
    Student(Student s) {
        this.rollNo = s.rollNo;
        this.name = s.name;
        this.cgpa = s.cgpa;
    }

    // Method to display student details
    void display() {
        System.out.println("Roll No: " + rollNo + " | Name: " + name + " | CGPA: " + cgpa);
    }
}

public class ConstructorDemo {
    public static void main(String[] args) {
        // Creating instances using all 3 constructors
        Student s1 = new Student();                     // Calls Default Constructor
        Student s2 = new Student(101, "Ananya", 8.9);   // Calls Parameterized Constructor
        Student s3 = new Student(s2);                   // Calls Copy Constructor (copies s2 into s3)

        s1.display();
        s2.display();
        s3.display();
    }
}

Output:

Roll No: 0 | Name: Not Assigned | CGPA: 0.0
Roll No: 101 | Name: Ananya | CGPA: 8.9
Roll No: 101 | Name: Ananya | CGPA: 8.9

(Note: Having multiple constructors in the same class with different parameter lists, as shown above, is called Constructor Overloading).


5. Comparison: Constructor vs Method

Basis Constructor Method (Member Function)
1. Purpose Used to initialize the state (fields) of a newly created object. Used to expose behavior / perform operations on an object.
2. Name Must have the exact same name as the Class. Can have any valid identifier name (should not be same as class name).
3. Return Type Has no return type (not even void). Must have a return type (void, int, String, etc.).
4. Invocation Invoked implicitly (automatically) by the new keyword. Invoked explicitly by the programmer (s1.display()).
5. Default Provision Compiler provides a default constructor if none is written. Compiler never provides any default method.
6. Inheritance Constructors are NOT inherited by subclasses. Non-private methods are inherited by subclasses.

💡 Exam Preparation Tips for DAVV BCA

  • “What is a Copy Constructor in Java? Does Java provide a default copy constructor?” This is a classic DAVV 5-mark question. State clearly that unlike C++, Java does not provide a default copy constructor, and write the Student(Student s) code above.
  • Always include the Constructor vs Method table when asked a long question on Constructors.